瘋狂 Android 講義, 4/e –彈出菜單(PopupMenu) P181~P182

瘋狂 Android 講義, 4/e –彈出菜單(PopupMenu) P181~P182

瘋狂 Android 講義, 4/e –彈出菜單(PopupMenu) P181~P182


資料來源:

    https://github.com/daichangya/book/tree/master/android

    https://pan.baidu.com/s/1d_xYJI0UQ_1tQzSj_V_NIg 提取码:70ch


XML code – popup_menu

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
	<item
		android:id="@+id/search"
		android:icon="@android:drawable/ic_menu_search"
		android:title="查找" />
	<item
		android:id="@+id/add"
		android:icon="@android:drawable/ic_menu_add"
		android:title="添加" />
	<item
		android:id="@+id/edit"
		android:icon="@android:drawable/ic_menu_edit"
		android:title="编辑">
		<menu>
			<item
				android:id="@+id/copy"
				android:title="复制" />
			<item
				android:id="@+id/cut"
				android:title="剪切" />
			<item
				android:id="@+id/paste"
				android:title="粘贴" />
		</menu>
	</item>
	<item
		android:id="@+id/exit"
		android:title="隐藏菜单" />
</menu>


XML code – activity_main

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
	xmlns:android="http://schemas.android.com/apk/res/android"
	android:layout_width="match_parent"
	android:layout_height="match_parent"
	android:orientation="vertical">
	<Button
		android:id="@+id/bn"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:layout_gravity="center"
		android:onClick="onPopupButtonClick"
		android:text="单击我" />
</LinearLayout>


JAVA code

package org.crazyit.ui;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.PopupMenu;
import android.widget.Toast;

/**
 * Description:<br>
 * 网站: <a href="http://www.crazyit.org">疯狂Java联盟</a><br>
 * Copyright (C), 2001-2020, Yeeku.H.Lee<br>
 * This program is protected by copyright laws.<br>
 * Program Name:<br>
 * Date:<br>
 *
 * @author Yeeku.H.Lee kongyeeku@163.com<br>
 * @version 1.0
 */
public class MainActivity extends Activity
{
	private PopupMenu popup;
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		Button button = findViewById(R.id.bn);
		// 创建PopupMenu对象
		popup = new PopupMenu(this, button);
		// 将R.menu.popup_menu菜单资源加载到popup菜单中
		getMenuInflater().inflate(R.menu.popup_menu, popup.getMenu());
		// 为popup菜单的菜单项单击事件绑定事件监听器
		popup.setOnMenuItemClickListener(item -> {
			switch (item.getItemId())
			{
				// 隐藏该对话框
				case R.id.exit: popup.dismiss();break;
				default:
					// 使用Toast显示用户单击的菜单项
					Toast.makeText(MainActivity.this,
					"您单击了【" + item.getTitle() + "】菜单项",
							Toast.LENGTH_SHORT).show();
					break;
			}
			return true;
		});
	}
	public void onPopupButtonClick(View button)
	{
		popup.show();
	}
}

發表迴響

你的電子郵件位址並不會被公開。 必要欄位標記為 *