答案 0 :(得分:4)
让我们从框框开始:
/res/drawable/count_frame.xml
<?xml version="1.0" encoding="utf-8"?>
<inset xmlns:android="http://schemas.android.com/apk/res/android"
android:inset="2dp">
<shape
android:shape="rectangle">
<corners android:radius="2dp"/>
<solid android:color="@android:color/transparent"/>
<stroke
android:width="2dp"
android:color="#FF404040"/>
</shape>
</inset>
该count_frame
框将围绕TextView
:
/res/layout/menu_action_count_view.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView android:id="@+id/text"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="24dp"
android:layout_height="24dp"
android:layout_margin="12dp"
android:background="@drawable/count_frame"
android:gravity="center"
android:textColor="#FF000000"
android:textSize="13sp"
android:textStyle="bold"
tools:text="4"/>
此TextView
将成为菜单项的操作视图。 (使用app:
命名空间,因为我假设您正在使用AppCompatActivity
):
/res/menu/menu_main.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/action_result_view"
android:title="@string/count"
app:actionLayout="@layout/menu_action_count_view"
app:showAsAction="always"/>
</menu>
现在,在onCreateOptionsMenu
覆盖中,您将获得操作视图并进行设置。我们假设您的计数在private int mCount;
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
TextView count = (TextView) menu.findItem(R.id.action_result_view).getActionView();
count.setText(Integer.toString(mCount)); // so the int isn't mistaken for a resource id!
count.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// do your action here
}
});
return true;
}
当计数发生变化时,请致电supportInvalidateOptionsMenu()
。
如果您想在点击此边框文本视图时显示溢出菜单,请在onCreateOptionsMenu
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
final Menu m = menu;
final MenuItem item = menu.findItem((R.id.action_result_view));
TextView count = (TextView) menu.findItem(R.id.action_result_view).getActionView();
count.setText(Integer.toString(mCount)); // so the int isn't mistaken for a resource id!
count.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
m.performIdentifierAction(item.getItemId(), 0);
}
});
return true;
}