Modify /res/menu/main.xml to define menu items.
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/action_settings"
android:orderInCategory="100"
android:showAsAction="never"
android:title="@string/action_settings"/>
<item
android:id="@+id/action_up"
android:orderInCategory="100"
android:showAsAction="ifRoom|withText"
android:icon="@android:drawable/arrow_up_float"
android:title="Up"/>
<item
android:id="@+id/action_down"
android:orderInCategory="100"
android:showAsAction="ifRoom|withText"
android:icon="@android:drawable/arrow_down_float"
android:title="Down"/>
<item
android:id="@+id/action_other"
android:orderInCategory="100"
android:showAsAction="ifRoom"
android:icon="@drawable/ic_launcher"
android:title="Other"/>
</menu>
To load menu, override onCreateOptionsMenu() method to inflate R.menu.main. It's loaded in default generated code.
To handle menu item selected, override onOptionsItemSelected() method.
MainActivity.java
package com.example.androidmenu;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case R.id.action_settings:
Toast.makeText(getApplicationContext(),
"Setting...",
Toast.LENGTH_SHORT).show();
break;
case R.id.action_up:
Toast.makeText(getApplicationContext(),
"Up...",
Toast.LENGTH_SHORT).show();
break;
case R.id.action_down:
Toast.makeText(getApplicationContext(),
"Down...",
Toast.LENGTH_SHORT).show();
break;
case R.id.action_other:
Toast.makeText(getApplicationContext(),
"Other...",
Toast.LENGTH_SHORT).show();
break;
default:
Toast.makeText(getApplicationContext(),
"Unknown...",
Toast.LENGTH_SHORT).show();
break;
}
//Return false to allow normal menu processing to proceed,
//true to consume it here.
return false;
}
}
Next:
- Show and hide menu item programatically
No comments:
Post a Comment