1
我打算在我的android應用程序中添加Chrome瀏覽器的功能(請參閱下面屏幕截圖中的箭頭),其中一個數字將顯示在操作欄菜單中,並在其周圍顯示邊框。我怎樣才能做到這一點?如何在android動作欄菜單項中顯示文字周圍的邊框?
我打算在我的android應用程序中添加Chrome瀏覽器的功能(請參閱下面屏幕截圖中的箭頭),其中一個數字將顯示在操作欄菜單中,並在其周圍顯示邊框。我怎樣才能做到這一點?如何在android動作欄菜單項中顯示文字周圍的邊框?
讓我們開始與箱形框架:
/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()
。
如果你想顯示在這個鑲上的TextView的自來水溢出菜單,在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;
}
變化工作使用下面的代碼。但我面臨着一個問題。該菜單項不再可點擊。另外我沒有使用AppCompatActivity。 –
我打算在點擊這個有邊框的文本視圖時顯示一個溢出菜單。 –
我可以解決這個問題,我已經更新了您的解決方案。非常感謝。 –