Friday, August 20, 2010

关于组菜单的操作

在菜单创建代码后面加上如下一句,则会使一组菜单成为单选状态。
 menu_send.setGroupCheckable(0, true, true);

代码:
      menu.setHeaderTitle(R.string.backup_conmenu);
            SubMenu menu_send=menu.addSubMenu("send");
            menu_send.add(0,menu_email,0,"email");
            menu_send.add(0,menu_wifi,0,"wifi");
            menu_send.setGroupCheckable(0, true, true);
            menu_send.setGroupEnabled(0, false);


SDK中的一句话应该如何理解:

This will display a checkbox with the menu item (unless it's in the Icon Menu). When the item is selected, the onOptionsItemSelected() callback is called as usual. It is here that you must set the state of the checkbox. You can query the current state of the item with isChecked() and set the checked state with setChecked(). Here's what this looks like inside theonOptionsItemSelected() callback:

  switch (item.getItemId()) {
case VIBRATE_SETTING_ID:
 
if (item.isChecked()) item.setChecked(false);
 
else item.setChecked(true);
 
return true;
...这里为什么要不断设置单选框的状态?
}
我在实际代码中这样:

    @Override
    public boolean onContextItemSelected(MenuItem item) {
//      AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
    TextView tview3=(TextView)findViewById(R.id.hello);
     switch (item.getItemId()) {
      case menu_email:
      tview3.setText("your data will send by email");
        return true;
      case menu_wifi:
      tview3.setText("your data will send by wifi");
        return true;
      case menu_apple:
      if (item.isChecked()) item.setChecked(false);
      else item.setChecked(true);
      tview3.setText("your favorite is apple");
      return true;
      case menu_pear:
      if (item.isChecked()) item.setChecked(false);
      else item.setChecked(true);
      tview3.setText("your favorite is pear");
      return true;
      case menu_ear:
      if (item.isChecked()) item.setChecked(false);
      else item.setChecked(true);
      tview3.setText("your favorite is ear");
      
      return true;
      case menu_egg:
//      if (item.isChecked()) item.setChecked(false);
//      else item.setChecked(true);
      tview3.setText("your favorite is egg");
      return true;
      default:
        return super.onContextItemSelected(item);
      }
     }

似乎也没有什么问题。

No comments:

Post a Comment