我有一个popupWindow,我用它来显示谷歌地图,但一旦它打开我似乎无法关闭它,我试图设置后退按钮关闭它但不能调用onBackButtonClick覆盖,因为我在片段内。似乎没有做任何事情
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_go, container, false);
mRouteBtn = (Button) rootView.findViewById(R.id.routeBtn);
mRouteBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
View popupView = getActivity().getLayoutInflater().inflate(R.layout.fragment_map, null);
mPopupWindow = new PopupWindow(popupView,
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
// If the PopupWindow should be focusable
mPopupWindow.setFocusable(true);
mPopupWindow.showAtLocation(getActivity().findViewById(R.id.routeBtn), Gravity.CENTER, 0, 0);
mPopupWindow.update(0, 0, 800, 800); //don't hardcode
后退按钮代码部分:
mPopupWindow.getContentView().setOnKeyListener( new View.OnKeyListener(){
@Override
public boolean onKey( View v, int keyCode, KeyEvent event ){
if( keyCode == KeyEvent.KEYCODE_BACK ){
mPopupWindow.dismiss();
return true;
}
return false;
}
} );
}
});
好的排序,在按照 Deepak Singh的建议后我开始工作了,虽然当我重新打开它时,由于尝试重新创建仍然存在的视图,我遇到了崩溃的问题。这是我的工作代码供将来参考:
固定版本:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_go, container, false);
mRouteBtn = (Button) rootView.findViewById(R.id.routeBtn);
mRouteBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (mPopupView != null) {
ViewGroup parent = (ViewGroup) mPopupView.getParent();
if (parent != null)
parent.removeView(mPopupView);
}
try {
mPopupView = getActivity().getLayoutInflater().inflate(R.layout.fragment_map, null);
} catch (InflateException e) {
/* map is already there, just return view as it is */
}
mPopupWindow = new PopupWindow(mPopupView,
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
mPopupWindow.setOutsideTouchable(true);
mPopupWindow.showAtLocation(getActivity().findViewById(R.id.routeBtn), Gravity.CENTER, 0, 0);
mPopupWindow.update(0, 0, 800, 800); //don't hardcode
mPopupView.findViewById(R.id.doneBtn).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mPopupWindow.dismiss();
}
});
}
});
答案 0 :(得分:4)
在弹出式窗口布局中添加一个按钮,然后使用popupView.findviewbyid(id)
找到按钮的ID,然后在此按钮上设置 clicklisener 并致电mPopupWindow.dismiss()
;。
你也可以试试这个:
popupView.setOutsideTouchable(true);
popupView.setFocusable(true);
答案 1 :(得分:0)
添加到您的代码popupWindow.setOutsideTouchable(true);
答案 2 :(得分:0)
根据this answer,你需要在弹出窗口中设置一个可绘制的背景。
我测试了它,你甚至不需要自己处理OnKeyListener
。
这足以使'后退按钮'工作:
popupWindow.setBackgroundDrawable(new ColorDrawable());
popupWindow.setFocusable(true);