基于可用屏幕大小的Android PopupWindow放置
问题描述:
我想在android中创建自定义popupWindow。我手边有两个问题 1.如何根据可用的屏幕大小放置popupwindow(左,右,上,下)。例如 弹出窗口链接到的按钮 a。如果它位于左上角,它应该打开在按钮底部 b。如果它位于屏幕的左下角,弹出应该在按钮顶部的右侧打开基于可用屏幕大小的Android PopupWindow放置
- 如何在弹出窗口附加到一个视图(如一个按钮)
答
首先,你必须确定你的弹出windown的布局。 例子:
<?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>
接下来,创建该处理您的弹出windown
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);
如果你把在ListView你的PopupWindow,将宽度设置为WRAP_CONTENT将不起作用。为了设定PopupWindow适当的宽度,你就必须在节目添加这个()方法:
// force the popupwindow width to be the listview width
listview.measure(
View.MeasureSpec.UNSPECIFIED,
View.MeasureSpec.UNSPECIFIED)
setWidth(listview.getMeasuredWidth());
我希望它可以帮助您的问题! 很高兴帮助你!
答
使用layout.setGravity(Gravity.<use any>)
放置布局。假设弹出窗口使用该布局。
也看到此链接: https://developer.android.com/reference/android/view/Gravity.html
+0
示例 - 锚点视图(按钮)位于屏幕的左下角。然后,弹出窗口应该位于按钮的右侧或顶部。 –
如何根据可用的屏幕宽度来放置popupwindow。 –