Rumah > Soal Jawab > teks badan
我在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
sendiri tidak mempunyai antara muka seperti Activity#onBackPressed()
, jadi Activity
perlu memaklumkan secara proaktif 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;
}
}