1.点击Button按钮显示弹窗 效果图如下 在主xml文件设置一个button按钮
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:layout_height="match_parent"
android:layout_width="match_parent"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android" >
<Button
android:text="弹出PopupWindow"
android:onClick="doubleClick"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
新建一个xml文件,命名为popup_view.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@mipmap/ic_launcher"
android:orientation="vertical">
<Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp"
android:text="上海"
android:textSize="18sp"/>
<Button
android:id="@+id/btn2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp"
android:text="北京"
android:textSize="18sp"/>
</LinearLayout>
java文件关键代码
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void doubleClick(View view) {
View popupView = getLayoutInflater().inflate(R.layout.popup_view, null);
PopupWindow popupWindow = new PopupWindow(popupView,
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT,true);
popupWindow.showAsDropDown(view);
}
2.给弹窗外设置背景 在java代码中加入
popupWindow.setBackgroundDrawable(getResources().getDrawable(R.drawable.troye));
3.弹出的两个按钮设置其他事件 因为两个Button按钮是在popupView中的,所以在java代码中要通过popupView去获取按钮
public void doubleClick(View view) {
View popupView = getLayoutInflater().inflate(R.layout.popup_view, null);
Button btn1 = popupView.findViewById(R.id.btn1);
Button btn2 = popupView.findViewById(R.id.btn2);
PopupWindow popupWindow = new PopupWindow(popupView,
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT,true);
popupWindow.setBackgroundDrawable(getResources().getDrawable(R.drawable.troye));
popupWindow.showAsDropDown(view);
btn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.e(TAG, "onClick: 你是住在上海吗" );
popupWindow.dismiss();
}
});
btn2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.e(TAG, "onClick: 你是住在北京吗" );
}
});
}
}
|