【Android初级】如何动态添加菜单项(附源码+避坑)

我们平时在开发过程中,为了灵活多变,除了使用静态的菜单,还有动态添加菜单的需求。今天要分享的功能如下:

  1. 在界面的右上角有个更多选项,点开后,有两个子菜单:关于和退出

  2. 点击“关于”,弹出一个对话框,显示一句话

  3. 点击“退出”,弹出一个对话框,用户点击“确定”,关闭整个页面;点击“取消”,不关闭页面

实现思路如下:

  1. 复写 onCreateOptionsMenu 方法,在该方法内调用Menu的add方法,动态添加菜单,并设置菜单的顺序和内容
  2. 复写 onOptionsItemSelected 方法,在该方法内处理菜单的点击事件
  3. 再单独提供两个方法,分别用于实现“关于”对话框和“退出对话框”的显示

源码如下:

1、主Activity

`import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import androidx.annotation.NonNull;
import com.example.memorydemo.R;

public class SimpleMenu extends Activity {
private static final String TAG = "SimpleMenu";
@Override
protected void onCreate(Bundle onSavedInstance) {
super.onCreate(onSavedInstance);
setContentView(R.layout.simple_menu);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // 添加一个 id 为 0,顺序为 0 的“关于”菜单
    menu.add(0, 0, 0, "About");

    // 添加一个 id 为 1,顺序为 1 的“退出”菜单
    menu.add(0, 1, 1, "Exit");
    Log.i(TAG, "call onCreateOptionsMenu");
    return true;
}

@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
    super.onOptionsItemSelected(item);
    // 这里的 itemId 就是上面add方法的第二个参数
    switch (item.getItemId()) {
        case 0:
            showDialog();
            break;

        case 1:
            showExitDialog();
            break;

        default:

    }
    return true;
}

private void showDialog() {
    new AlertDialog.Builder(this)
            .setTitle("About")
            .setMessage("This is just a demo.")
            .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                }
            })
            .show();
}

private void showExitDialog() {
    new AlertDialog.Builder(this)
            .setTitle("Exit")
            .setMessage("Are you sure to EXIT?")
            .setPositiveButton("Sure", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    finish();
                }
            })
            .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                }
            })
            .show();
}

}`

2、简单的布局文件simple_menu.xml,把TextView 放屏幕中间:

`

<TextView
        android:text="This is a simple menu demo."
        android:layout_width="wrap_content"
        android:layout_gravity="center"
        android:gravity="center"
        android:layout_height="wrap_content" android:id="@+id/textView5" android:layout_weight="1"/>

`

3、效果图如下:

这里有个“坑”要注意:

如果该Activity或整个应用使用了父主题为“Theme.AppCompat.Light.DarkActionBar”的主题,比如:

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">

菜单不会显示!!!

posted @ 2021-01-27 23:32  snowyeti  阅读(390)  评论(0编辑  收藏  举报