I am able to create an OptionMenu, see code below. But in my program the problem is that I have to write logic in every activity.
If I have an application with 10 activities. I have to write code for the menu everywhere.
I want to create a single menu for the whole application. No matter where i am. If I click on the Hardware Menu key then I must be able to get 开发者_StackOverflow社区to the Menu. How do I create this type of universal Menu?
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;
public class SimpleOptionMenu extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.animation_test);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.icon:
Toast.makeText(this, "You pressed the icon!", Toast.LENGTH_LONG)
.show();
break;
case R.id.text:
Toast.makeText(this, "You pressed the text!", Toast.LENGTH_LONG)
.show();
break;
case R.id.icontext:
Toast.makeText(this, "You pressed the icon and text!",
Toast.LENGTH_LONG).show();
break;
}
return true;
}
}
animation_test.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button
android:id="@+id/btn_ani"
android:layout_alignParentTop="true"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Click to start animation"/>
</RelativeLayout>
Simply create a new Activity with the onOptionsSelected method and extend this created Activity.
class OptionsActivity extends Activity {
public boolean onOptionsItemSelected(MenuItem item) {
...
}
}
class SimpleOptionsMenu extends OptionsActivity {
...
}
If you want to create the same menu with the same actions everywhere you can create an abstract class ActivityHelper which extends Activity. You can override onCreateOptionsMenu and onOptionsItemSelected to put your logic. Then you just have to extends BaseActivity in your activities.
That should do the trick!
Cheers,
精彩评论