是否有一种方法,我们可以实现onBackPressed()在Android片段类似的方式,我们实现在Android活动?
因为Fragment的生命周期没有onBackPressed()。在android3.0片段中是否有其他替代方法来覆盖onBackPressed() ?
是否有一种方法,我们可以实现onBackPressed()在Android片段类似的方式,我们实现在Android活动?
因为Fragment的生命周期没有onBackPressed()。在android3.0片段中是否有其他替代方法来覆盖onBackPressed() ?
当前回答
我是这样做的,对我很管用
简单的界面
FragmentOnBackClickInterface.java
public interface FragmentOnBackClickInterface {
void onClick();
}
示例实现
MyFragment.java
public class MyFragment extends Fragment implements FragmentOnBackClickInterface {
// other stuff
public void onClick() {
// what you want to call onBackPressed?
}
然后在activity中重写onBackPressed
@Override
public void onBackPressed() {
int count = getSupportFragmentManager().getBackStackEntryCount();
List<Fragment> frags = getSupportFragmentManager().getFragments();
Fragment lastFrag = getLastNotNull(frags);
//nothing else in back stack || nothing in back stack is instance of our interface
if (count == 0 || !(lastFrag instanceof FragmentOnBackClickInterface)) {
super.onBackPressed();
} else {
((FragmentOnBackClickInterface) lastFrag).onClick();
}
}
private Fragment getLastNotNull(List<Fragment> list){
for (int i= list.size()-1;i>=0;i--){
Fragment frag = list.get(i);
if (frag != null){
return frag;
}
}
return null;
}
其他回答
使用导航组件,你可以这样做:
Java
public class MyFragment extends Fragment {
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// This callback will only be called when MyFragment is at least Started.
OnBackPressedCallback callback = new OnBackPressedCallback(true /* enabled by default */) {
@Override
public void handleOnBackPressed() {
// Handle the back button event
}
});
requireActivity().getOnBackPressedDispatcher().addCallback(this, callback);
// The callback can be enabled or disabled here or in handleOnBackPressed()
}
...
}
科特林
class MyFragment : Fragment() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// This callback will only be called when MyFragment is at least Started.
val callback = requireActivity().onBackPressedDispatcher.addCallback(this) {
// Handle the back button event
}
// The callback can be enabled or disabled here or in the lambda
}
...
}
在我的解决方案(Kotlin);
我使用onBackAlternative函数作为BaseActivity的参数。
BaseActivity
abstract class BaseActivity {
var onBackPressAlternative: (() -> Unit)? = null
override fun onBackPressed() {
if (onBackPressAlternative != null) {
onBackPressAlternative!!()
} else {
super.onBackPressed()
}
}
}
我有一个函数在BaseFragment上设置onBackPressAlternative。
碱基片段
abstract class BaseFragment {
override fun onStart() {
super.onStart()
...
setOnBackPressed(null) // Add this
}
//Method must be declared as open, for overriding in child class
open fun setOnBackPressed(onBackAlternative: (() -> Unit)?) {
(activity as BaseActivity<*, *>).onBackPressAlternative = onBackAlternative
}
}
然后我的onBackPressAlternative就可以用于片段了。
子片段
override fun setOnBackPressed(onBackAlternative: (() -> Unit)?) {
(activity as BaseActivity<*, *>).onBackPressAlternative = {
// TODO Your own custom onback function
}
}
片段: 创建一个BaseFragment,放置一个方法:
public boolean onBackPressed();
活动:
@Override
public void onBackPressed() {
List<Fragment> fragments = getSupportFragmentManager().getFragments();
if (fragments != null) {
for (Fragment fragment : fragments) {
if (!fragment.isVisible()) continue;
if (fragment instanceof BaseFragment && ((BaseFragment) fragment).onBackPressed()) {
return;
}
}
}
super.onBackPressed();
}
你的活动将在附加的和可见的片段上运行,并对它们中的每一个调用onBackPressed(),如果其中一个返回'true'(意味着它已经被处理,所以没有进一步的操作),则中止。
你可以像这样使用父活动的onBackPressedDispatcher:
val backpress = requireActivity().onBackPressedDispatcher.addCallback(viewLifecycleOwner, true) {
// here dispatcher works for any action when back pressed
}
你也可以从fragment中启用/禁用backpress按钮,如下所示:
backpress.isEnabled = true/false
在活动生命周期中,当我们使用FragmentActivity或AppCompatActivity时,总是android返回按钮处理FragmentManager事务。要处理backstack,我们不需要处理它的backstack计数或标记任何东西,但我们应该在添加或替换片段时保持专注。请找到以下片段来处理后退按钮的情况,
public void replaceFragment(Fragment fragment) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
if (!(fragment instanceof HomeFragment)) {
transaction.addToBackStack(null);
}
transaction.replace(R.id.activity_menu_fragment_container, fragment).commit();
}
在这里,我不会为我的主页片段添加回堆栈,因为它是我应用程序的主页。如果将addToBackStack添加到HomeFragment,那么应用程序将等待删除活动中的所有片段,然后我们将得到空白屏幕,所以我保持以下条件,
if (!(fragment instanceof HomeFragment)) {
transaction.addToBackStack(null);
}
现在,你可以看到之前添加的片段在活动和应用程序将退出时,到达HomeFragment。您还可以查看以下片段。
@Override
public void onBackPressed() {
if (mDrawerLayout.isDrawerOpen(Gravity.LEFT)) {
closeDrawer();
} else {
super.onBackPressed();
}
}