瘋狂 Android 講義, 4/e – 浮動視窗(PopupWindow) P168~P169

瘋狂 Android 講義, 4/e – 浮動視窗(PopupWindow) P168~P169

瘋狂 Android 講義, 4/e – 浮動視窗(PopupWindow) P168~P169


資料來源:
    https://github.com/daichangya/book/tree/master/android
    https://pan.baidu.com/s/1d_xYJI0UQ_1tQzSj_V_NIg 提取码:70ch
    https://rx1226.pixnet.net/blog/post/348577561-%5Bandroid%5D-popupwindow%E5%92%8Calertdialog%E7%9A%84%E5%B7%AE%E5%88%A5


XML Code – popup.xml

<?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:gravity="center_horizontal"
	android:orientation="vertical">

	<ImageView
		android:layout_width="240dp"
		android:layout_height="wrap_content"
		android:src="@drawable/duke" />

	<Button
		android:id="@+id/close"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:text="关闭" />
</LinearLayout>


XML Code – activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
	android:orientation="vertical"
	android:layout_width="match_parent"
	android:layout_height="match_parent"
	android:gravity="center_horizontal">
	<Button android:id="@+id/bn"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:text="弹出Popup窗口"/>
</LinearLayout>


Java Code

package org.crazyit.ui;

import android.app.Activity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.PopupWindow;

/**
 * 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
{
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		// 加载R.layout.popup对应的界面布局文件
		View root = this.getLayoutInflater().inflate(R.layout.popup, null);
		// 创建PopupWindow对象
		PopupWindow popup = new PopupWindow(root, 560, 720);
		Button button = findViewById(R.id.bn);
		button.setOnClickListener(view ->
			// 以下拉方式显示
			// popup.showAsDropDown(view);
			// 将PopupWindow显示在指定位置
			popup.showAtLocation(findViewById(R.id.bn), Gravity.CENTER, 20, 20));
		// 获取PopupWindow中的“关闭”按钮,并绑定事件监听器
		root.findViewById(R.id.close).setOnClickListener(view -> popup.dismiss() /* ① */);
	}
}

PS.

    01.PopupWindow和AlertDialog都可以達到Android的彈出對話框效果

    02.其最主要的差別就是AlertDialog在彈出時背景的Activity上的動作都可以繼續執行,而PopupWindow在彈出時, 背景的一切活動都會停止

發表迴響

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