我根据menu制作了一个简单的应用程序.java代码是
public class MainActivity extends Activity {
TextView tv;
CheckBox chb;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv=(TextView)findViewById(R.id.textView);
chb=(CheckBox)findViewById(R.id.chbInFlate);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
menu.add(0, 1, 0, "add");
menu.add(0, 2, 0, "edit");
menu.add(0, 3, 3, "delete");
menu.add(1, 4, 1, "copy");
menu.add(1, 5, 2, "paste");
menu.add(1, 6, 4, "exit");
return true;
}
public boolean OnPrepareOptionsMenu(Menu menu)
{
if(chb.isChecked()) {
Log.d("my", "aaa");
menu.setGroupVisible(1, true);
} else {
Log.d("my", "bbb");
menu.setGroupVisible(1, false);
}
return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
Log.d("my", "bbb");
StringBuilder sb=new StringBuilder();
sb.append("Menu Item");
sb.append("\r\n Group id="+ String.valueOf(item.getGroupId()));
sb.append("\r\n Item id="+ String.valueOf(item.getItemId()));
sb.append("\r\n Order ="+ String.valueOf(item.getOrder()));
sb.append("\r\n Title="+ item.getTitle());
tv.setText(sb.toString());
return super.onOptionsItemSelected(item);
}
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.add.MainActivity" >
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:text="@string/hello_world" />
<CheckBox
android:id="@+id/chbInFlate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true"
android:layout_marginTop="67dp"
android:text="CheckBox" />
</RelativeLayout>
最初所有6个菜单项都可见,无论是否选中复选框.....现在放入log.d方法后,当选择一个菜单项时,我的logcat过滤器中的消息正确显示,但是log.d没有响应isChecked方法。为什么会这样?
答案 0 :(得分:0)
只要复选框状态发生变化,您就应该致电invalidateOptionsMenu()
。
OnPrepareOptionsMenu()
有错误的情况。它应该是onPrepareOptionsMenu()
。请务必添加@Override
注释以避免此类问题。
答案 1 :(得分:0)
答案 2 :(得分:0)
试试这个:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv=(TextView)findViewById(R.id.textView);
chb=(CheckBox)findViewById(R.id.chbInFlate);
invalidateOptionsMenu()
}