gpt4 book ai didi

java - 单击按钮时尝试打开弹出窗口

转载 作者:太空宇宙 更新时间:2023-11-04 10:40:44 26 4
gpt4 key购买 nike

我试图在单击按钮时打开一个弹出窗口(模式窗口)。我不知道它在Java中是如何工作的,我看过很多教程但无法弄清楚。这是我的按钮。

    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/white"
>

<LinearLayout
android:layout_margin="50dp"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<LinearLayout
android:layout_gravity="center"
android:orientation="vertical"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"/>
<Button
//This is the button that should open a modal window
android:id="@+id/btnfruit"
android:background="@mipmap/iconfruit"
android:layout_width="100dp"
android:layout_height="100dp" />
<Button
android:layout_marginTop="100dp"
android:background="@mipmap/vegetable"
android:layout_width="100dp"
android:layout_height="100dp" />
<Button
android:layout_marginTop="200dp"
android:background="@mipmap/protein"
android:layout_width="100dp"
android:layout_height="100dp" />

<Button
android:layout_marginTop="300dp"
android:background="@mipmap/dairy"
android:layout_width="100dp"
android:layout_height="100dp" />
<Button
android:layout_marginTop="400dp"
android:background="@mipmap/grain"
android:layout_width="100dp"
android:layout_height="100dp" />
<ImageView
android:layout_alignParentBottom="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#FFFFFF"/>
</RelativeLayout>

this is the modal window.

<?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="400dp"
android:layout_gravity="center"
android:orientation="vertical"
android:padding="5dp"
>
<TextView

android:layout_width="30dp"
android:layout_height="30dp"
android:text="X"
android:textStyle="bold"
android:layout_gravity="end"
android:gravity="center"/>
<Button
android:id="@+id/btnaddfruit"
android:layout_width="100dp"
android:layout_height="50dp"
android:text="Add Item"/>
</LinearLayout>

我想我的问题是,MainActivity.java 发生了什么,或者我可以将其直接编码到按钮吗?预先感谢您的时间和答复。

最佳答案

无论您的 Button 对象位于哪个类,我都会假设 MainActivity,创建一个 PopupWindow 对象(您必须导入该类。在按钮的 onClick() 方法内部,初始化它并设置位置

PopupWindow myWindow = new PopupWindow(View content, int height, int width, true);
myWindow.showAtLocation(View content, Gravity.CENTER, 0, 0);

显然你需要用你自己的值来填写未填写的参数。为了获得所需的 View 对象,您必须使用 LayoutInflater 为弹出窗口创建一个新的 View。 .

关于java - 单击按钮时尝试打开弹出窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48997999/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com