菜单项的自定义视图 [英] Custom view for Menu Item

查看:60
本文介绍了菜单项的自定义视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要具有动态菜单项,即用户定义的颜色的圆圈,如下所示:

I need to have dynamic Menu Item, a circle of user defined color, like this:

触摸此菜单项将打开一个颜色选择器.

touching this menu item will open a color picker.

现在,我有示例ColorPickerIcon,它扩展了View

Now, I have sample ColorPickerIcon which extends View

public class ColorPickerIcon extends View {

private Paint mPaint;
private int mColor;

private final int mRadius = 20;

public ColorPickerIcon(Context context) {
    super(context);

    mColor = Color.BLACK;
    mPaint = createPaint();
}

public ColorPickerIcon(Context context, AttributeSet attrs) {
    super(context, attrs);

    mColor = Color.BLACK;
    mPaint = createPaint();
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    canvas.drawCircle(0, 0, mRadius, mPaint);
}

public void setPaintColor(int color) {
    mColor = color;
}

private Paint createPaint() {

    Paint temp = new Paint();
    temp.setAntiAlias(true);
    temp.setStyle(Paint.Style.STROKE);
    temp.setStrokeJoin(Paint.Join.ROUND);

    temp.setStrokeWidth(6f);
    temp.setColor(mColor);

    return temp;

}

}

和menu.xml

<item
    android:id="@+id/menu_pick_color"
    android:title="@string/pick_color"
    yourapp:showAsAction="always"
    yourapp:actionViewClass="com.example.widgets.ColorPickerIcon"/>

<item
    android:id="@+id/menu_clear"
    android:icon="@null"
    android:title="@string/clear"
    yourapp:showAsAction="always"/>

<item
    android:id="@+id/menu_save"
    android:icon="@null"
    android:title="@string/save"
    yourapp:showAsAction="always"/>

但是它不能以这种方式工作,我既不能实例化该类,也不能对其进行渲染.有没有办法将自定义类和自定义动态视图用作菜单项?

But it doesn't work this way, neither can I instantiate the class nor it's rendered. Is there a way to use custom class and custom dynamic view as Menu Item?

推荐答案

好,所以事实证明比这更简单.

Okay, so it turned out to be simpler than that.

在DrawingActivity中

In the DrawingActivity

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menu_drawing, menu);

    MenuItem colorPicker = menu.findItem(R.id.menu_pick_color);

    ShapeDrawable circle = new ShapeDrawable(new OvalShape());
    circle.getPaint().setColor(Color.GREEN);
    circle.setIntrinsicHeight(120);
    circle.setIntrinsicWidth(120);
    circle.setBounds(0, 0, 120, 120);

    colorPicker.setIcon(circle);

    return true;
}

在menu.xml中

<item
    android:id="@+id/menu_pick_color"
    android:title="@string/pick_color"
    yourapp:showAsAction="always"/>

仅此而已.

这篇关于菜单项的自定义视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆