使用以下代码时出现以下错误
The method onKeyDown(int, KeyEvent) is undefined for the type SherlockFragment
public boolean onKeyDown(int KeyCode, KeyEvent event) {
if ((KeyCode == KeyEvent.KEYCODE_BACK) && web.canGoBack()) {
web.goBack();
return true;
}
return super.onKeyDown(KeyCode, event);
}
答案 0 :(得分:1)
活动应该管理后退按钮而不是片段。如果您希望片段管理onKeyDown,则可以在OnKeyListener
getView()
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.left, container, false);
view.setOnKeyListener( new OnKeyListener() {
@Override
public boolean onKey( View v, int keyCode, KeyEvent event ) {
// here your code
}
});
return view;
}
答案 1 :(得分:1)
经过少量研究。我找到了这个 ! 希望它的帮助。
root =(ViewGroup) inflater.inflate(R.layout.setting_f_other, container, false);
root.setOnKeyListener( new OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event ) {
if (keyCode == KeyEvent.KEYCODE_BACK){
//Do something
}
return false;
}
});
答案 2 :(得分:1)
我会将这种事情从你的片段中删除。以下代码在我的MainActivity中为我工作,有4个选项卡,每个选项卡都有自己的Web视图。
@Override
public void onBackPressed() {
// TODO Auto-generated method stub
int currPage = mPager.getCurrentItem();
WebView wv = null;
switch (currPage) {
case 0:
wv = (WebView) mPager.getChildAt(currPage).findViewById(R.id.webView1);
break;
case 1:
wv = (WebView) mPager.getChildAt(currPage).findViewById(R.id.webView2);
break;
case 2:
wv = (WebView) mPager.getChildAt(currPage).findViewById(R.id.webView3);
break;
case 3:
wv = (WebView) mPager.getChildAt(currPage).findViewById(R.id.webView4);
break;
}
if (wv != null) {
if (wv.canGoBack()) {
wv.goBack();
} else {
super.onBackPressed();
}
} else {
super.onBackPressed();
}
}
编辑:我在第四个选项卡上遇到了麻烦,我的解决方案是在我的片段(Tab0.java)中设置webView静态。然后直接在我的主要活动中引用它。
switch (currPage) {
case 0:
wv = Tab0.webView;
break;
case 1:
wv = Tab1.webView;
break;
case 2:
wv = Tab2.webView;
break;
case 3:
wv = Tab3.webView;
break;
}