Saturday, January 10, 2009

Icons in Options Menu in Android (Code)

Here is a brief topic on how to set icons on options menu in Android, this is an extension to Options Menu in Android.

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

public class Main extends Activity {
  private int searchBtnId = Menu.FIRST;
  private int scheduleBtnId = Menu.FIRST + 1;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.setContentView(R.layout.main);
  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    MenuItem searchMItm = menu.add(Menu.NONE,
searchBtnId ,searchBtnId,"Search");
    searchMItm.setIcon(R.drawable.search);
    MenuItem scheduleMItm = menu.add(Menu.NONE,
scheduleBtnId ,scheduleBtnId,"Schedule" );
    scheduleMItm.setIcon(R.drawable.schedule);
    return super.onCreateOptionsMenu(menu);
  }
}


Quick Explanation
MenuItem scheduleMItm = menu.add(Menu.NONE, scheduleBtnId ,scheduleBtnId,"Schedule" );
menu.add returns a MenuItem in which we can use its method setIcon, scheduleMItm.setIcon(R.drawable.schedule);, here we imported a png into our folder and named it as schedule.
 
Source Code
Main.java
 
References
MenuItem
Options Menu in Android (Code)

Update History
   Jan 17, 2012 - Visual Update
Post a Comment