九、PopupWindow
常用方法
1. setContentView(View contentView):设置 PopupWindow显示的View
2. showAsDropDown(View anchor):相对某个控件的位置(正左下方),无偏移
3. showAsDropDown(View anchor, int xoff, int yoff):相对某个控件的位置,有偏移
4. setFocusable(boolean focusable)设置是否获取焦点
5. setBackgroundDraywable(Drawable background) 设置背景
6. dismiss()关闭弹窗
7. setAnimationStyle(int animationStyle)设置加载动画
8. setTouchable(boolean touchable)设置触摸使能
9. setOutside Touchable(boolean touchable)设置PopupWindow外面的触摸使能
源码示例
1.ui主界面源码
<?xml version="1.0" encoding="utf-8"?> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" xmlns:android="http://schemas.android.com/apk/res/android"> <Button android:text="弹出PopupWindow" android:onClick="Btn_Clink" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout>
2. Popupwindow的ui界面
<?xml version="1.0" encoding="utf-8"?> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:background="@mipmap/ic_launcher" xmlns:android="http://schemas.android.com/apk/res/android"> <Button android:text="北京" android:id="@+id/btn_BeiJing" android:layout_width="wrap_content" android:layout_height="wrap_content"/> <Button android:text="上海" android:id="@+id/btn_Shanghai" android:layout_width="wrap_content" android:layout_height="wrap_content"/> </LinearLayout>
3.后台源代码
package com.example.mypopupwindow; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.PopupWindow; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } /** * 按钮点击事件 * */ public void Btn_Clink(View view) { //获取View View popupview=getLayoutInflater().inflate(R.layout.popup_view,null); //获取按钮 Button btn1=popupview.findViewById(R.id.btn_BeiJing); Button btn2=popupview.findViewById(R.id.btn_Shanghai); //声明PopupWindow PopupWindow popupWindow=new PopupWindow(popupview, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true); //设置背景色 popupWindow.setBackgroundDrawable(getResources().getDrawable(R.drawable.bg)); //显示1 popupWindow.showAsDropDown(view); //显示2 //popupWindow.showAsDropDown(view,view.getWidth(),view.getHeight()); //设置Popupwindow的内部的按钮点击事件 btn1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Log.e("leo", "onClick: 点击了”北京“按钮"); //关闭弹窗 popupWindow.dismiss(); } }); btn2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Log.e("leo", "onClick: 点击了”上海“按钮" ); //关闭弹窗 popupWindow.dismiss(); } }); } }