0

林內使用以下代碼未定義的onkeydown SherlockFragment

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); 
    } 

回答

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(); 
    } 
} 

編輯:我遇到了麻煩我的第四選項卡,併爲我的解決辦法是設置web視圖在我的片段(Tab0.java)靜態的。然後直接參考我的主要活動。

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; 
    } 
+1

感謝您的代碼,這太棒了! –

1

當活動應該管理後退按鈕不是片段得到以下錯誤。如果你想片段管理的onkeydown,您可以通過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

附加OnKeyListener,在返回的視圖中完成一些研究之後。我找到了這個 ! 希望它的幫助。

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; 

         } 
       });