利用Menu,需要覆盖这两个方法:
public boolean onCreateOptionsMenu(Menu menu)
public boolean onOptionsItemSelected(MenuItem item)
代码如下:
package android.neugls.amenu; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.widget.TextView; public class AMenu extends Activity { private TextView tvTip; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); tvTip=(TextView)findViewById(R.id.tvTip); } @Override public boolean onCreateOptionsMenu(Menu menu) { // TODO Auto-generated method stub menu.add(0, 1, 1, R.string.about); menu.add(0,2,2,R.string.exit); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { // TODO Auto-generated method stub int ItemID=item.getItemId(); switch(ItemID){ case 1: DisplayAbout(); break; case 2: finish(); break; } return super.onOptionsItemSelected(item); } private void DisplayAbout(){ tvTip.setText(R.string.strAbout); } }
onCreateOptionsMenu在用户按钮Menu键,Menu被创建时调用。在上面的代码中我们往Menu中加了两个MenuItem
onOptionsItemSelected在用户选择一个MenuItem时被调用,我们可以通过MenuItem.getItemId()来判断用户按了那个
按钮,然后进行相应的处理。
finish()结束Activity.