1. 程式人生 > >android 在fragment中如何監聽返回鍵,home鍵

android 在fragment中如何監聽返回鍵,home鍵

在activity中用keydown很容易實現對返回鍵的監聽,但是這個函式不能再fragment中過載。 

通過我嘔心瀝血的尋找,終於找到了解決辦法,對其他物理按鍵的監聽也同理。 
Java程式碼  收藏程式碼
  1. public class phonerecorder extends Fragment {  
  2.     View listview;  
  3.     public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {  
  4.         listview = (View) inflater.inflate(R.layout.phonerecorder, null
    );  
  5.         mListView = (ListView) listview.findViewById(R.id.listView);  
  6.         init();  
  7.         mListView.setOnItemClickListener(clickitemlistener);  
  8.         listview.setFocusable(true);//這個和下面的這個命令必須要設定了,才能監聽back事件。  
  9.         listview.setFocusableInTouchMode(true);  
  10.         listview.setOnKeyListener(backlistener);  
  11.         return listview;  
  12.     }  
  13.   private View.OnKeyListener backlistener = new View.OnKeyListener() {  
  14.         @Override  
  15.         public boolean onKey(View view, int i, KeyEvent keyEvent) {  
  16.             if (keyEvent.getAction() == KeyEvent.ACTION_DOWN) {  
  17.                 if (i == KeyEvent.KEYCODE_BACK) {  //表示按返回鍵 時的操作
      
  18.                     if (!rootpatch.equals(currentfilepach) && currentfilepach != null) {  
  19.                         File file = new File(currentfilepach);  
  20.                         openDir2(file.getParent().toString());  
  21.                         currentfilepach = file.getParent().toString();  
  22.                         return true;  
  23.                     } //後退  
  24.                     return false;    //已處理  
  25.                 }  
  26.             }  
  27.             return false;  
  28.         }  
  29.     };  
  30. }