制作基于XML布局的菜单的程序代码

最终的结果:

image

制作方法:

1.添加res/menu/menu.xml

menu.xml代码:

<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/about" android:title="关于">
    </item>
</menu>

 

2.Activity.java中添加的代码

package com.zhai.android.gps;

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

public class Main extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }

    public boolean onCreateOptionsMenu(Menu menu) {

        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu, menu);
        return true;
    }

    public boolean onOptionItemSelected(MenuItem item) {
        int item_id = item.getItemId();

        switch (item_id) {

        case R.id.about:
            // TO DO 点击菜单后执行的动作

            break;
        }

        return true;
    }

}