次のような、ユーザー定義の色の円である動的なメニュー項目が必要です。
このメニュー項目をタッチするとカラーピッカーが開きます。
さて、Viewを拡張したサンプルColorPickerIconがあります
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"/>
しかし、この方法では動作せず、クラスをインスタンス化することもレンダリングすることもできません。カスタム クラスとカスタム動的ビューをメニュー項目として使用する方法はありますか?
ベストアンサー1
必要なのは、アイテムに必要なビューを含むレイアウト ファイルを作成し、メニューでアイテムを宣言するときに、次のようにレイアウトを割り当てることです。
<item
android:id="@+id/menu_pick_color"
android:title="@string/pick_color"
app:showAsAction="always"
app:actionLayout="@layout/my_custom_item"/>
以上です!
編集:
実行時にカスタム項目にアクセスしてその色を変更するには、次の操作を実行します。
アクティビティ(またはフラグメント)で、onPrepareOptionsMenu
(すでに「onCreateOptionsMenu」でメニューを膨らませていると仮定して)をオーバーライドします。
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
//Get a reference to your item by id
MenuItem item = menu.findItem(R.id.menu_pick_color);
//Here, you get access to the view of your item, in this case, the layout of the item has a FrameLayout as root view but you can change it to whatever you use
FrameLayout rootView = (FrameLayout)item.getActionView();
//Then you access to your control by finding it in the rootView
YourControlClass control = (YourControlClass) rootView.findViewById(R.id.control_id);
//And from here you can do whatever you want with your control
return true;
}