android菜单Menu结合popupWindow的用法实现弹出在屏幕任意位置!
程序员文章站
2022-05-31 14:02:37
...
个人学习笔记
xml代码:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/bg"
tools:context="com.lhh.weimenu.MainActivity">
<!--微信标题-->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/text_title"
android:textColor="#FFFFFF"
android:textSize="25sp"
/>
<!--菜单按钮-->
<Button
android:layout_width="40dp"
android:layout_height="40dp"
android:id="@+id/btn_menu"
android:layout_alignParentRight="true"
android:onClick="OnMenu"
android:background="@drawable/btn_add"/>
</RelativeLayout>
界面布局:
activity核心代码:
public void OnMenu(View view) {
View popupWindow_view = getLayoutInflater().inflate(R.layout.menu,null,false);
popupWindow =new PopupWindow(popupWindow_view, ActionBar.LayoutParams.WRAP_CONTENT,ActionBar.LayoutParams.WRAP_CONTENT,true);
//控制弹出位置
popupWindow.showAtLocation(findViewById(R.id.btn_menu),0,0,0);
popupWindow_view.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if(popupWindow != null && popupWindow.isShowing()){
popupWindow.dismiss();
popupWindow = null;
}
return false;
}
});
}
一共有四个参数,findViewById(R.id.btn_menu)是你写的菜单布局id,第二个是gravity(0表示左上角,),第三个是距离原点x轴的偏移量(即gravity的偏移量),第四个是距离原点y轴的偏移量。注意:屏幕的x轴方向是向右的,y轴方向是向下的。
接下来改变值查看效果:
popupWindow.showAtLocation(findViewById(R.id.btn_menu), Gravity.TOP,0,0);
popupWindow.showAtLocation(findViewById(R.id.btn_menu), Gravity.BOTTOM,0,0);
还有Gravity.LEFT,Gravity.RIGHT,Gravity.CENTER,自己可以试着改。
下面两位大佬的代码看了受益颇深,也可以看一下(附上链接):
链接1:https://blog.csdn.net/Andy_l1/article/details/79731440
链接2:https://www.cnblogs.com/popfisher/p/5608436.html