有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java试图在单击按钮时打开弹出窗口

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

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

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

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

this is the modal window.

        <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout
        xmlns:安卓="http://schemas.安卓.com/apk/res/安卓"
        安卓:layout_width="match_parent"
        安卓:layout_height="400dp"
        安卓:layout_gravity="center"
        安卓:orientation="vertical"
        安卓:padding="5dp"
     >
        <TextView

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

我想我的问题是,主要活动是什么。java或者我可以直接编码到按钮吗?提前感谢您的时间和回答


共 (1) 个答案

  1. # 1 楼答案

    在Button对象所在的任何类中,我都假设MainActivity创建一个PopupWindow对象(必须导入该类。在Button的onClick()方法中,初始化它并设置位置)

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

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