【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">

菜單不會顯示!!!

Tags: