How to switch to new Activity from menu?

笑着哭i 提交于 2019-12-13 14:13:31

问题


I have a menu and would like to open a new Activity when the user clicks on the menu item:

@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
        case R.id.add_symbol:
           System.out.println("ADD SYMBOL CLICKED!");
           Intent myIntent = new Intent(this.getContext(), AddStocksActivity.class);
           startActivityForResult(myIntent, 0);
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }

I'm not sure how to create my Intent properly

Compiler Error:

The method getContext() is undefined for the type Main

回答1:


Since Main extends Activity (which extends Context), you can do:

Intent myIntent = new Intent(this, AddStocksActivity.class)



回答2:


this is what I do

public boolean onCreateOptionsMenu(Menu menu){
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.options_menu, menu);

    MenuItem item1 = menu.findItem(R.id.menu_item_a);
    Intent intent1 = new Intent(this, A.class);
    item1.setIntent(intent1);

    MenuItem item2 = menu.findItem(R.id.menu_item_b);
    Intent intent2 = new Intent(this, B.class);
    item2.setIntent(intent2);

}

hope it helps




回答3:


Change this.getContext() to this.getApplicationContext()

You are trying to call a method that doesn't exist.




回答4:


In your activity class do

Context mContext;

In your onCreate() do

mContext = this

then in your Options thing, do

Intent myIntent = new Intent(this.getContext(), AddStocksActivity.class);



回答5:


 Intent myIntent = new Intent(getApplicationContext(), AddStocksActivity.class);

or

Intent myIntent = new Intent(this, AddStocksActivity.class)


来源:https://stackoverflow.com/questions/3587761/how-to-switch-to-new-activity-from-menu

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!