请有人帮忙 -
我有一个弹出窗口,我在一个名为pop的函数中创建了一个弹出窗口。我还有另一个功能,当用户点击弹出窗口中的按钮时,它会关闭popupWindow。我为解雇创建了一个单独的功能。我想将popupwindow传递给dismiss函数 - 这是最好的方法。我想重用dismiss函数。
public class MainActivity extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void popup(View v) {
LayoutInflater layoutInflater = (LayoutInflater) getBaseContext().getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = layoutInflater.inflate(R.layout.activity_alert_dialog,null);
final PopupWindow popup= new PopupWindow(layout, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
View vi=(View) findViewByID(R.id.Layout);
popup.showAtLocation(vi, 0, 20, -50);
}
public void dismiss(View v) {
popup.dismiss();
}
}
我的解雇方法是在资源布局文件中执行的:
<Button
android:text="cancel"
android:onClick="dismiss"/>
答案 0 :(得分:1)
尝试以下代码:每次拨打popup()
时都会创建弹出窗口。
public class MainActivity extends AppCompatActivity {
private PopupWindow mPopup = null;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void popup(View v) {
LayoutInflater layoutInflater = (LayoutInflater) getBaseContext().getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = layoutInflater.inflate(R.layout.activity_alert_dialog,null);
// Use global variable instead of local.
//final PopupWindow popup= new PopupWindow(layout, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
mPopup= new PopupWindow(layout, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
View vi=(View) findViewByID(R.id.Layout);
mPopup.showAtLocation(vi, 0, 20, -50);
}
public void dismiss(View v) {
if (mPopup != null && mPopup.isShowing()) {
mPopup.dismiss();
}
}
}
而且,我对mPopup.showAtLocation(vi, 0, 20, -50);
的位置值有疑问。它是y = -50
的正确位置吗?
我认为这个弹出窗口会显示出来。
答案 1 :(得分:0)
为PopupWindow创建全局变量。
private PopupWindow popup;
public void popup(View v) {
LayoutInflater layoutInflater = (LayoutInflater) getBaseContext().getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = layoutInflater.inflate(R.layout.activity_alert_dialog,null);
popup= new PopupWindow(layout, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
View vi=(View) findViewByID(R.id.Layout);
popup.showAtLocation(vi, 0, 20, -50);
}
public void dismiss(View v) {
popup.dismiss();
}