Sunday, 8 January 2012

Show as Action Item with icon

Modify from last article "Add and respond Action Items on Action Bar", we can display individual item seperately on with icon, instead of within the overflow action item.

Show as Action Item with icon

Notice the the code of menu0 in onCreateOptionsMenu() method:
package com.exercise.AndroidActionBar;

import android.app.ActionBar;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
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) {
super.onCreateOptionsMenu(menu);

/*
* menu.add(int groupId, int itemId, int order, CharSequence title);
*/
MenuItem menu0 = menu.add(0, 0, 0, "Action Item 0");
{
menu0.setIcon(R.drawable.ic_launcher);
menu0.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
}
menu.add(0, 1, 1, "Action Item 1");
menu.add(0, 2, 2, "Action Item 2");
menu.add(0, 3, 3, "Action Item 3");
menu.add(0, 4, 4, "Action Item 4");

return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

switch(item.getItemId()){
case 0:
Toast.makeText(AndroidActionBarActivity.this,
"Action Item 0 selected!",
Toast.LENGTH_LONG).show();
return true;
case 1:
Toast.makeText(AndroidActionBarActivity.this,
"Action Item 1 selected!",
Toast.LENGTH_LONG).show();
return true;
case 2:
Toast.makeText(AndroidActionBarActivity.this,
"Action Item 2 selected!",
Toast.LENGTH_LONG).show();
return true;
case 3:
Toast.makeText(AndroidActionBarActivity.this,
"Action Item 3 selected!",
Toast.LENGTH_LONG).show();
return true;
case 4:
Toast.makeText(AndroidActionBarActivity.this,
"Action Item 4 selected!",
Toast.LENGTH_LONG).show();
return true;
default:
return false;

}

}
}


next:
- Show Action Item with icon and text

No comments:

Post a Comment