How to switch to new Activity from menu?

2019-07-01 10:09发布

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

5条回答
别忘想泡老子
2楼-- · 2019-07-01 10:55

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);
查看更多
聊天终结者
3楼-- · 2019-07-01 11:03

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

Intent myIntent = new Intent(this, AddStocksActivity.class)
查看更多
萌系小妹纸
4楼-- · 2019-07-01 11:03

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

查看更多
SAY GOODBYE
5楼-- · 2019-07-01 11:05
 Intent myIntent = new Intent(getApplicationContext(), AddStocksActivity.class);

or

Intent myIntent = new Intent(this, AddStocksActivity.class)
查看更多
啃猪蹄的小仙女
6楼-- · 2019-07-01 11:08

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

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

查看更多
登录 后发表回答