Android 实现点击按钮弹出窗口—PopupWindow
1.PopupWindow布局文件test_popup.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:orientation="vertical"
android:gravity="center_horizontal"
>
<Spinner
android:id="@+id/testSpinner"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:entries="@array/spinner"/>
<EditText
android:layout_width="300dp"
android:layout_height="40dp"
android:hint="参数1"/>
<EditText
android:layout_width="300dp"
android:layout_height="40dp"
android:hint="参数2"/>
<EditText
android:layout_width="300dp"
android:layout_height="40dp"
android:hint="参数3"/>
<EditText
android:layout_width="300dp"
android:layout_height="40dp"
android:hint="参数4"/>
<Button
android:id="@+id/startTest"
android:layout_width="150dp"
android:layout_height="45dp"
android:text="开始测试"
android:textColor="@color/white"
android:background="@color/colorAccent" />
</LinearLayout>
2.设置按钮布局及点击事件,触发窗口popup
<TextView
android:id="@+id/iv_test"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="测试"
android:textSize="14sp"
android:layout_alignParentRight="true"
android:layout_marginTop="14dp"
android:layout_marginRight="70dp"
android:onClick="popUpWindow"
android:textColor="@color/white"/>
点击事件popUpWindow
public void popUpWindow(View view){
//创建窗口
PopupWindow popupWindow=new PopupWindow(this);
popupWindow.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
View popUpView=LayoutInflater.from(this).inflate(R.layout.test_popup, null);
popupWindow.setContentView(popUpView);
popupWindow.setOutsideTouchable(false);
popupWindow.setFocusable(true);
popupWindow.setTouchable(true);
popupWindow.setBackgroundDrawable(new ColorDrawable(Color.WHITE));
//弹出创建显示在按钮下面
popupWindow.showAsDropDown(view);
testSpinner=popUpView.findViewById(R.id.testSpinner);
testSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
String str=(String)testSpinner.getSelectedItem();
d("提示","测试"+str);
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
3.注意
PopupWindow初始化一些控件,需要用到findViewById()在布局中找到对应的控件,注意是要用
View popUpView=LayoutInflater.from(this).inflate(R.layout.test_popup, null);
testSpinner=popUpView.findViewById(R.id.testSpinner);//指定View:popUpView