我在Fragment的布局中放置了一个WebView,想监听WebView的返回键,该如何实现?
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
getView().setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && webview.canGoBack()) {
webview.goBack();
return true;
}
return false;
}
});
}
这样监听没用
ringa_lee2017-04-18 09:07:04
Fragment
本身是没有 Activity#onBackPressed()
这样的接口的, 所以需要 Activity
主动通知 Fragment
:
public class ActivityA extends Activity {
... ...
@Override
public void onBackPressed() {
FragmentA fragment = findFragmentA();
if (fragment.onBackPressed()) {
return ;
}
super.onBackPressed();
}
}
public class FragmentA extends Fragment {
public boolean onBackPressed() {
if (webview.canGoBack()) {
webview.goBack();
return true;
}
return false;
}
}