【问题标题】:Android PopupWindow placement based on available screen size基于可用屏幕尺寸的 Android PopupWindow 位置
【发布时间】:2017-10-09 12:09:31
【问题描述】:

我想在 android 中创建我的自定义 popupWindow。我手头有 2 个问题 1.如何根据可用的屏幕尺寸放置弹出窗口(左,右,上,下)。例如 弹出窗口链接到的按钮 一个。如果它放在左上角,它应该在按钮的底部打开 b.如果它在屏幕的左下角,弹出窗口应该在按钮顶部的右侧或顶部打开

  1. 如何将弹出窗口附加到视图(例如按钮)

【问题讨论】:

    标签: android


    【解决方案1】:

    首先,您必须为弹出窗口定义布局。 示例:

    <?xml version="1.0" encoding="utf-8"?>   
    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
    
        <Button
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:text="Button"
            android:id="@+id/button">
        </Button>
    
    </LinearLayout>
    

    接下来,创建一个处理弹出窗口的类

    import android.content.Context;
    import android.view.Gravity;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup.LayoutParams;
    import android.view.WindowManager;
    import android.widget.ListView;
    import android.widget.PopupWindow;
    
    public class PopupMenu extends PopupWindow
    {
        Context     m_context;
    
        public PopupMenu(Context context)
        {
            super(context);
    
            m_context = context;
    
            setContentView(LayoutInflater.from(context).
                 inflate(R.layout.popup_menu, null));
    
            setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
            setWidth(WindowManager.LayoutParams.WRAP_CONTENT);
        }
    
        public void show(View anchor)
        {
            // you can edit display location is here
            showAtLocation(anchor, Gravity.CENTER, 0, 0);
        }
    }
    

    您可以通过以下代码轻松使用它:

    PopupMenu popupMenu = new PopupMenu(context);
    popupMenu.show(view);
    

    如果您在 PopupWindow 中放置一个列表视图,将宽度设置为 WRAP_CONTENT 将不起作用。为了正确设置 PopupWindow 的宽度,您必须在 show() 方法中添加它:

     // force the popupwindow width to be the listview width
    listview.measure(
                     View.MeasureSpec.UNSPECIFIED,
                     View.MeasureSpec.UNSPECIFIED)
    setWidth(listview.getMeasuredWidth());
    

    希望对您的问题有所帮助! 很高兴为您提供帮助!

    【讨论】:

    • 如何根据可用的屏幕宽度放置弹出窗口。
    • 问题是如何根据可用的屏幕宽度(或高度)绘制(高于或低于事件位置)
    【解决方案2】:

    使用layout.setGravity(Gravity.&lt;use any&gt;) 放置布局。假设弹出窗口使用该布局。

    另见此链接: https://developer.android.com/reference/android/view/Gravity.html

    【讨论】:

    • 示例 - 锚视图(按钮)出现在屏幕的左下方。然后弹出窗口应该出现在按钮的右侧或顶部。
    猜你喜欢
    • 1970-01-01
    • 2016-09-17
    • 2021-11-23
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多