How to switch to new Activity from menu?

2019-07-01 11:00发布

问题:

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)