我想在菜单项上显示一些动态文本。到目前为止,这是我的代码。
菜单文件
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".MyActivity">
<item
android:id="@+id/search"
android:title="Search"
android:icon="@drawable/magnify"
app:showAsAction="ifRoom"/>
<item
android:id="@+id/Cart"
android:title="Cart"
android:icon="@drawable/cart"
app:showAsAction="ifRoom"/>
<item
android:id="@+id/badge"
android:title="Cart2"
android:actionLayout="@layout/actionbar_badge_layout"
android:icon="@drawable/cart"
app:showAsAction="always" />
</menu>
actinbar_badge_layout.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="48dp"
android:layout_height="fill_parent"
android:layout_gravity="right" >
<!-- Menu Item Image -->
<ImageView
android:layout_width="48dp"
android:layout_height="fill_parent"
android:clickable="true"
android:src="@drawable/cart" />
<!-- Badge Count -->
<TextView
android:id="@+id/actionbar_notifcation_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:padding="4dp"
android:text="99"
android:textColor="#FF0000" />
</RelativeLayout>
和活动
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_my2, menu);
RelativeLayout badgeLayout = (RelativeLayout) menu.findItem(R.id.badge).getActionView();
TextView tv = (TextView) badgeLayout.findViewById(R.id.actionbar_notifcation_textview);
tv.setText("12");
return true;
}
它在
中给出了空指针异常错误TextView tv = (TextView) badgeLayout.findViewById(R.id.actionbar_notifcation_textview);
有人可以帮我解决这个问题吗?
答案 0 :(得分:0)
我不确定但是试试这个:
TextView tv = (TextView) menu.findViewById(R.id.actionbar_notifcation_textview);
代替
TextView tv = (TextView) badgeLayout.findViewById(R.id.actionbar_notifcation_textview);
答案 1 :(得分:0)
请检查this answer
简而言之 - 尝试使用app:actionLayout
代替android:actionLayout
。