这里就是我想和它的工作!
在的onCreate():
private PopupWindow popupWindow;
someButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final LayoutInflater inflater = (LayoutInflater) appContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View popupView = inflater.inflate(R.layout.popupwindow_view, null, false);
popupWindow = new PopupWindow(popupView, WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT);
popupWindow.setBackgroundDrawable(new BitmapDrawable());
popupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
popupWindow.setOutsideTouchable(false);
CustomSearchView searchView = (CustomSearchView) popupView.findViewById(R.id.customSearchView);
popupWindow.showAsDropDown(someButton, 50, -30);
}
});
确保有这个在你的活动:
@Override
public void onBackPressed() {
if (popupWindow != null && popupWindow.isShowing()) {
Toast.makeText(context, "Activity Back Pressed - PopupWindow showing!", Toast.LENGTH_SHORT).show();
} else {
super.onBackPressed();
}
我的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">
<com.package.name.CustomSearchView
android:layout_width="match_parent"
android:id="@+id/customSearchView"
android:background="@android:color/black"
android:layout_height="match_parent"></com.package.name.CustomSearchView>
</LinearLayout>
CustomSearchView.java
public class CustomSearchView extends SearchView {
Context context;
public CustomSearchView(Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
}
@Override
public boolean dispatchKeyEventPreIme(KeyEvent event) {
if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
clearFocus();
Toast.makeText(context, "CustomSearchView Back Pressed", Toast.LENGTH_SHORT).show();
return false;
} else {
return super.dispatchKeyEventPreIme(event);
}
}
}
当我执行此实现时,CustomSearchView的dispatchKeyEventPreIme
不称为BUT Activity的OnBackPressed()
确实被调用。
如您所见,当按下后退按钮时,我会输入Toast
,并且每次都会调用它。试试看。它不关闭PopupWindow。
试试这个.. popupWindow.setCancelable(false) – Meenal
@MeenalSharma popupWindow没有'setCancelable'方法。 'AlertDialog'和'Dialog'确实。 –