Пользовательский вид для пункта меню
Мне нужно иметь динамический элемент меню, круг определенного пользователем цвета, например:
![enter image description here]()
Прикосновение к этому пункту меню откроет элемент выбора цвета.
Теперь у меня есть образец ColorPickerIcon, который расширяет 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"/>
Но это не работает таким образом, я не могу создать экземпляр класса и не отображаться. Есть ли способ использовать пользовательский класс и пользовательский динамический вид в качестве пункта меню?
Ответы
Ответ 1
Итак, оказалось, что это проще.
В 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"/>
![enter image description here]()
Что все.
Ответ 2
Что вам нужно сделать, это создать файл макета с представлением, которое вы хотите для элемента, когда вы объявите элемент в меню, назначьте макет следующим образом:
<item
android:id="@+id/menu_pick_color"
android:title="@string/pick_color"
app:showAsAction="always"
app:actionLayout="@layout/my_custom_item"/>
И что это!
EDIT:
Чтобы получить доступ к настраиваемому элементу и изменить его цвет во время выполнения, вы можете сделать это.
В вашей деятельности (или фрагменте) переопределите 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;
}