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 m开发者_如何转开发ethod getContext() is undefined for the type Main
Since Main
extends Activity
(which extends Context
), you can do:
Intent myIntent = new Intent(this, AddStocksActivity.class)
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
Change this.getContext()
to this.getApplicationContext()
You are trying to call a method that doesn't exist.
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);
Intent myIntent = new Intent(getApplicationContext(), AddStocksActivity.class);
or
Intent myIntent = new Intent(this, AddStocksActivity.class)
精彩评论