Roman Roman - 3 months ago 24
Android Question

Custom view for Menu Item

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

enter image description here

touching this menu item will open a color picker.

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;

}

}


and 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?

Answer

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

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;
}

in menu.xml

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

enter image description here

That's all.