是否有一种方法,我们可以实现onBackPressed()在Android片段类似的方式,我们实现在Android活动?

因为Fragment的生命周期没有onBackPressed()。在android3.0片段中是否有其他替代方法来覆盖onBackPressed() ?


当前回答

像这样执行 Fragment_1 -> Fragment_2 -> Fragment_3

    Button btn = (Button) rootView.findViewById(R.id.your_button_id);
    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Fragment_2 nextFrag= new Fragment_2();
            getActivity().getSupportFragmentManager().beginTransaction()
                    .replace(R.id.content_frame, nextFrag,getTag())
                    .addToBackStack(null)
                    .commit();

        }
    });

Fragment_3 -> Fragment_2 -> Fragment_1

Step_1:在Base Activity中创建一个可公开访问的字符串

step2:每当一个新的Fragment被激活时,在Base Activity中改变String的值

Step_3:然后添加onBackPressed()方法,并将字符串值传递给另一个方法,其中fagments可以被替换

在基础活动中

public static String currentFragment=null;

@Override
public void onBackPressed() 
{
        displayPreviousFragment(currentFragment);
}

public void displayPreviousFragment(String currentFragment)
{
    //creating fragment object
    Fragment fragment = null;

    //initializing the fragment object which is selected
    switch (currentFragment)
    {
        case "Fragment_2"    :   fragment = new Fargment_1();     break;
        case "Fragment_3"    :   fragment = new Fragment_2();     break;
    }

    //replacing the fragment
    if (fragment != null) {
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.replace(R.id.frame_to_replace_fragment, fragment);
        ft.commit();
    }
}

在Fragment_2 在OnCreateView方法内

BaseActivity.currentFragment="Fragment_2";

在Fragment_3 在OnCreateView方法内

BaseActivity.currentFragment="Fragment_3";

其他回答

根据@ hammer的回答,这里是伪代码,它应该如何工作。 假设你的主活动名为BaseActivity,它有子片段(就像SlidingMenu库的例子一样)。 以下是步骤:

首先,我们需要创建接口和类,实现它的接口具有泛型方法

Create class interface OnBackPressedListener public interface OnBackPressedListener { public void doBack(); } Create class which implements skills of OnBackPressedListener public class BaseBackPressedListener implements OnBackPressedListener { private final FragmentActivity activity; public BaseBackPressedListener(FragmentActivity activity) { this.activity = activity; } @Override public void doBack() { activity.getSupportFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE); } } Since now, we will work on our code BaseActivity and its fragments Create private listener on top of your class BaseActivity protected OnBackPressedListener onBackPressedListener; create method to set listener in BaseActivity public void setOnBackPressedListener(OnBackPressedListener onBackPressedListener) { this.onBackPressedListener = onBackPressedListener; } in override onBackPressed implement something like that @Override public void onBackPressed() { if (onBackPressedListener != null) onBackPressedListener.doBack(); else super.onBackPressed(); in your fragment in onCreateView you should add our listener @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { activity = getActivity(); ((BaseActivity)activity).setOnBackPressedListener(new BaseBackPressedListener(activity)); View view = ... ; //stuff with view return view; }

瞧,现在当你在片段中单击返回时,你应该捕获你的自定义on back方法。

如果你需要在Fragment中实现,你应该使用接口。

另一方面,如果你需要在活动中实现,如eg。执行一个简单的finish()活动,执行以下操作:

YourActivity.kt

override fun onBackPressed() {
    Log.d(this.javaClass.simpleName, "onBackPressed() called")

    if (supportFragmentManager.fragments.any { it is YourFragment }) {
        finish()
        return
    }
}

没有人提到我如何调用活动?这个逻辑中的onBackPressed。

所以我创建了一个可能对你有用的扩展:

fun Fragment.onBackClick(callback: (onBackPressedCallback: OnBackPressedCallback) -> Unit) {
// This callback will only be called when MyFragment is at least Started.

    activity?.onBackPressedDispatcher?.addCallback(viewLifecycleOwner) {
        callback.invoke(this)
    }
}

现在激动人心的部分调用onBackPressed当你的逻辑完成:

片段中的示例使用:

onBackClick { 
        if (shouldBackFromFrag){
            //do your logic when pressed back
        }else{
            it.isEnabled = false //the key to disable the dispatcher
            activity?.onBackPressed()
        }
    }

简单地在onKeyUp()中做:

@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {

    if (keyCode == KeyEvent.KEYCODE_BACK) {
        // do something
        return true;  // return true if back handled, false otherwise
    }

    return super.onKeyUp(keyCode, event);
}

我知道已经太迟了,但我上周也遇到了同样的问题。没有一个答案能帮到我。然后我开始摆弄代码,这是可行的,因为我已经添加了片段。

在你的活动中,为ViewPager设置一个OnPageChangeListener,这样你就能知道用户什么时候在第二个活动中。如果他在第二个活动中,将布尔值设为true,如下所示:

    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.pager);
    mViewPager.setAdapter(mSectionsPagerAdapter);
    mViewPager.setCurrentItem(0);
    mViewPager.addOnPageChangeListener(new OnPageChangeListener() {

        @Override
        public void onPageSelected(int position) {
            // TODO Auto-generated method stub
                mSectionsPagerAdapter.instantiateItem(mViewPager, position);
                if(position == 1)
                    inAnalytics = true;
                else if(position == 0)
                    inAnalytics = false;
        }

        @Override
        public void onPageScrolled(int position, float arg1, int arg2) {
            // TODO Auto-generated method stub
        }

        @Override
        public void onPageScrollStateChanged(int arg0) {
            // TODO Auto-generated method stub

        }
    });

现在,无论何时按下后退按钮,都检查布尔值,并将当前项目设置为您的第一个片段:

@Override
public void onBackPressed() {
    if(inAnalytics)
        mViewPager.setCurrentItem(0, true);
    else 
        super.onBackPressed();
}