android 在fragment中如何監聽返回鍵,home鍵
阿新 • • 發佈:2019-01-27
在activity中用keydown很容易實現對返回鍵的監聽,但是這個函式不能再fragment中過載。
通過我嘔心瀝血的尋找,終於找到了解決辦法,對其他物理按鍵的監聽也同理。Java程式碼
- public class phonerecorder extends Fragment {
- View listview;
- public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
-
listview = (View) inflater.inflate(R.layout.phonerecorder, null
- mListView = (ListView) listview.findViewById(R.id.listView);
- init();
- mListView.setOnItemClickListener(clickitemlistener);
- listview.setFocusable(true);//這個和下面的這個命令必須要設定了,才能監聽back事件。
- listview.setFocusableInTouchMode(true);
-
listview.setOnKeyListener(backlistener);
- return listview;
- }
- private View.OnKeyListener backlistener = new View.OnKeyListener() {
- @Override
- public boolean onKey(View view, int i, KeyEvent keyEvent) {
- if (keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
-
if (i == KeyEvent.KEYCODE_BACK) { //表示按返回鍵 時的操作
- if (!rootpatch.equals(currentfilepach) && currentfilepach != null) {
- File file = new File(currentfilepach);
- openDir2(file.getParent().toString());
- currentfilepach = file.getParent().toString();
- return true;
- } //後退
- return false; //已處理
- }
- }
- return false;
- }
- };
- }