Modify from the article "Show Action Item with icon and text".
- Create a XML file /res/menu/menu.xml to define the menu items of the ActionBar.
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/itemid_0"
android:title="Action Item 0"
android:icon="@drawable/ic_launcher"
android:orderInCategory="0"
android:showAsAction="ifRoom|withText" />
<item android:id="@+id/itemid_1"
android:title="Action Item 1"
android:orderInCategory="0" />
<item android:id="@+id/itemid_2"
android:title="Action Item 2"
android:orderInCategory="0" />
<item android:id="@+id/itemid_3"
android:title="Action Item 3"
android:orderInCategory="0" />
</menu>
- Modify onCreateOptionsMenu() to inflate the XML file. Also modify onOptionsItemSelected() to change the itemId(s) accordingly.
package com.exercise.AndroidActionBar;
import android.app.ActionBar;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class AndroidActionBarActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button showActionBar = (Button)findViewById(R.id.showactionbar);
Button hideActionBar = (Button)findViewById(R.id.hideactionbar);
showActionBar.setOnClickListener(new Button.OnClickListener(){
@Override
public void onClick(View arg0) {
ActionBar actionBar = getActionBar();
actionBar.show();
}});
hideActionBar.setOnClickListener(new Button.OnClickListener(){
@Override
public void onClick(View arg0) {
ActionBar actionBar = getActionBar();
actionBar.hide();
}});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case R.id.itemid_0:
Toast.makeText(AndroidActionBarActivity.this,
"Action Item 0 selected!",
Toast.LENGTH_LONG).show();
return true;
case R.id.itemid_1:
Toast.makeText(AndroidActionBarActivity.this,
"Action Item 1 selected!",
Toast.LENGTH_LONG).show();
return true;
case R.id.itemid_2:
Toast.makeText(AndroidActionBarActivity.this,
"Action Item 2 selected!",
Toast.LENGTH_LONG).show();
return true;
case R.id.itemid_3:
Toast.makeText(AndroidActionBarActivity.this,
"Action Item 3 selected!",
Toast.LENGTH_LONG).show();
return true;
default:
return false;
}
}
}
Download the files.
Related:
- Split Action Bar for Android 4
No comments:
Post a Comment