Android菜单:如何在代码中使用条件动态更改菜单

时间:2015-03-17 00:34:08

标签: android android-optionsmenu

我尝试更改OptionMenu中的项目,具体取决于活动中是否选择了一个名称(来自Spinner),我试图在invalidateOptionsmenu()内使用spinner.setOnItemSelectedListener 然后在onPrepareOptionsMenu设置我的条件,但我收到一个错误:

"java.lang.ClassCastException: com.android.internal.view.menu.ActionMenuItemView cannot be cast to android.view.MenuItem"

我的代码:

public class MainActivity extends Activity {
    private long projectId;
    public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       datasource = new StatementDataSource(this);
       datasource.open();

       setContentView(R.layout.activity_main);

       //setting a spinner with simpleCursorAdapter
       ...
       public void onItemSelected(AdapterView<?> parent, View view, int position, long id){
           projectId = id;
           //trigger OptionsMenu to recreate
           invalidateOptionsMenu();
      }
 }

@Override
public boolean onPrepareOptionsMenu(Menu menu) {
    private String phoneNumber = datasource.getPhoneNumber(projectId);
    //checking if selected name has a phone number in the database
    if (!phoneNumber.isEmpty()){ //values might be null or empty
        menu.findItem(R.id.callButton).setVisible(true);
    } else {
        menu.findItem(R.id.callButton).setVisible(false);
    }
    return super.onPrepareOptionsMenu(menu);
  }

0 个答案:

没有答案