【Android】從無到有:手把手一步步教你使用最簡單的Fragment(三)
阿新 • • 發佈:2018-11-01
轉載請註明出處,原文連結:https://blog.csdn.net/u013642500/article/details/80585416
【本文適用讀者】
用程式碼建立並使用了 Fragment,新增 Fragment 之後,想要按返回鍵可以返回上一層 View。
【AS版本】
【方法1】
修改新增 Fragment 的相關程式碼。
getSupportFragmentManager().beginTransaction() .addToBackStack(null) .add(R.id.container, new BlankFragment()) .commit();
【方法2】
重寫 onBackPessed 方法。
@Override public void onBackPressed() { List<Fragment> fragments = getSupportFragmentManager().getFragments(); if (!fragments.isEmpty() && fragments.get(0) != null && fragments.get(0).isVisible()) { getSupportFragmentManager().beginTransaction().remove(fragments.get(0)).commit(); } else { super.onBackPressed(); }
【成果】
【相關連結】
從無到有:手把手一步步教你使用最簡單的 Fragment(一)
https://blog.csdn.net/u013642500/article/details/80515227
從無到有:手把手一步步教你使用最簡單的 Fragment(二)
https://blog.csdn.net/u013642500/article/details/80515227