Vitaly Menchikovsky Vitaly Menchikovsky - 2 months ago 16
Android Question

How to create a menu programmatically in Android?

Now I want to add it a menu on the bottom of the screen.
I wrote a lot of about but still didnt get how to do that.
My main problem is that I dont have an xml file on my main page.
its look liks that:

public class start extends ListActivity {
static final String[] COUNTRIES = new String[] {
"NEWS1", "NEWS2","RADIO"};
Intent intent;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

setListAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, COUNTRIES));

ListView lv = getListView();
lv.setTextFilterEnabled(true);

lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if (((TextView) view).getText().equals("NEWS1")){
intent = new Intent(start.this, NewsActivity.class);


how can I add a menu with an action.
please give me a example.
thanks

Answer

Ya its fine if you dont have an XML file in your main activity. You can still add menu to it by following this steps ->

  1. create an android XML file and select menu as type(It will get stored under res folder's menu sub folder).
  2. Now in your main activity code add this two methods ->

    public boolean onCreateOptionsMenu(Menu menu){
        getMenuInflater().inflate(R.menu.yourmenuxmlfilename, menu);
        return true;
    }
    public boolean onOptionsItemSelected(MenuItem item){
        switch(item.getItemId){
            case R.id.item1:
                // what you want to do with first button
                break;
            case .....
                break;
        }
        return true;
    }