如何制作一个简单的Android弹出窗口
这是一个更完整的例子。这是一个补充性答案,涉及一般情况下创建弹出窗口的过程,而不一定是OP问题的具体细节。(OP要求取消按钮,但这不是必需的,因为用户可以在屏幕上的任意位置单击以将其取消。)它看起来像下图。
设置弹出窗口的布局
向其中添加一个布局文件,res/layout该文件定义弹出窗口的外观。
popup_window.xml
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#62def8">
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_margin="30dp"
android:textSize="22sp"
android:text="This is a popup window."/>
充气并显示弹出窗口
这是示例中主要活动的代码。只要单击该按钮,弹出窗口就会膨胀并显示在活动上方。触摸屏幕上的任何位置均可关闭弹出窗口。
MainActivity.java
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onButtonShowPopupWindowClick(View view) {
// inflate the layout of the popup window
LayoutInflater inflater = (LayoutInflater)
getSystemService(LAYOUT_INFLATER_SERVICE);
View popupView = inflater.inflate(R.layout.popup_window, null);
// create the popup window
int width = LinearLayout.LayoutParams.WRAP_CONTENT;
int height = LinearLayout.LayoutParams.WRAP_CONTENT;
boolean focusable = true; // lets taps outside the popup also dismiss it
final PopupWindow popupWindow = new PopupWindow(popupView, width, height, focusable);
// show the popup window
// which view you pass in doesn't matter, it is only used for the window tolken
popupWindow.showAtLocation(view, Gravity.CENTER, 0, 0);
// dismiss the popup window when touched
popupView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
popupWindow.dismiss();
return true;
}
});
}
}
而已。大功告成