后退按钮按下处理程序

时间:2017-12-12 09:46:14

标签: android android-fragments fragment-backstack

我正在开发一款需要Navigation Drawer.的应用。此应用有1个MainActivity,上面有10个片段。当我单击MainActivity中的导航抽屉图标时,它将显示10 fragments,因此我可以选择每个。{/ p>

我选择fragment A,然后选择B,然后选择C ...到F.当我在fragment F并按下后退按钮时,它会将我带回fragment E,然后再返回它会带我到fragment D ... 我需要的是当我按下fragment中的后退按钮时,它需要转到navigationdrawer中的默认主页。

我搜索了SO并找到了1个类似的问题,但还没有答案,所以我不得不提出另一个问题

7 个答案:

答案 0 :(得分:2)

我想你可以尝试一下。在onBackPressed()

中添加此内容
if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
        for (int i = 0; i < getSupportFragmentManager().getBackStackEntryCount(); i++) {
            getSupportFragmentManager().popBackStack();
        }
    } else {
        super.onBackPressed();

    }

答案 1 :(得分:2)

下面是我的解决方案,

我使用下面的代码来更改片段:

fragmentManager = getFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();

if (fragmentA == null)
    fragmentA = new FragmentA();

fragmentTransaction.replace(R.id.container, fragmentA);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commitAllowingStateLoss();

如果您正在使用supportFragment,则使用getSupportFragmentManager()代替getFragmentManager()。

当你在那时执行背压时将下面的代码放入包含Fragment的Activity中。

@Override
public void onBackPressed() {
    super.onBackPressed();
    getFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
}

希望这个答案可以帮助你并解决你的问题。

答案 2 :(得分:1)

你试过吗

try {  
   activity.getSupportFragmentManager().popBackStackImmediate(n‌​ull,FragmentManager.POP_BACK_STACK_INCLUSIVE);
   } catch (IllegalStateException e)
  { 
     e.printStackTrace();
  }

答案 3 :(得分:1)

在这种情况下,请勿将Fragments添加到backStack。如果您不希望弹出fragment,只需替换每个onBackPressed()即可。

getSupportFragmentManager().beginTransaction().replace(R.id.containerFrame, new AFragment()).commit();

处理onBackPressed()

@Override
public void onBackPressed() {
    Fragment frag = getSupportFragmentManager().findFragmentById(R.id.containerFrame);
    if (frag instanceof HomeFragment) {
        // DO Onbackpress
        finish();
    } else {
        HomeFragment fragment = new HomeFragment()
        getSupportFragmentManager().beginTransaction().replace(R.id.containerFrame, fragment).commit();
    }
}

答案 4 :(得分:1)

* The purpose of this method is set The current display ui
 *
 * @param id the ui that has to be displayed
 */
public void setDisplay(int id) {
    if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
        mDrawerLayout.closeDrawer(GravityCompat.START);
    }

    HideKeyboard.hideKeyboard(HomepageActivity.this);
    Intent intent;
    switch (id) {
        //Open up home fragment
        case AppConstants.DISPLAY_HOME:
            if (!(mFragmentManager.findFragmentById(R.id.fragment_container) instanceof FragmentHome)) {
                mFragment = new FragmentHome();
                replaceFragment(mFragment, AppConstants.HOME_FRAGMENT);
            }
            break;
        //opens up the setting section
        case AppConstants.DISPLAY_SETTING:
            if (!(mFragmentManager.findFragmentById(R.id.fragment_container) instanceof FragmentSetting)) {
                mFragment = new FragmentSetting();
                replaceFragment(mFragment, AppConstants.SETTING_FRAGMENT);
            }
            break;
        //display the logout dialog
        case AppConstants.DISPLAY_LOGOUT:
            DialogManager.getInstance().showLogOutLogOut(this);
            break;
        //display the notification section
        case AppConstants.DISPLAY_NOTIFICATION:
            if (!(mFragmentManager.findFragmentById(R.id.fragment_container) instanceof FragmentNotification)) {
                mFragment = new FragmentNotification();
                replaceFragment(mFragment, AppConstants.NOTIFICATION_FRAGMENT);
            }
            break;

        default:
            //Setup Home Fragment as default fragment
            if (!(mFragmentManager.findFragmentById(R.id.fragment_container) instanceof FragmentHome)) {
                mFragment = new FragmentHome();
                replaceFragment(mFragment, AppConstants.HOME_FRAGMENT);
            }
            break;
    }
}

/ *  *通过替换任何现有的mFragment插入mFragment  *  * @param片段必须替换的片段  * @param命名片段的标签  * /

public void replaceFragment(final Fragment fragment, final String name) {
          if(mFragmentManager.findFragmentById(R.id.fragment_container)instanceof FragmentHome) {
                mFragmentManager.beginTransaction()
                        .replace(R.id.fragment_container, fragment, name)
                        .addToBackStack(name)
                        .commit();
            } else {
                mFragmentManager.beginTransaction()
                        .replace(R.id.fragment_container, fragment).
                        commit();
            }
      }

/ **      *此方法的目的是从堆栈中删除片段      * /     public void removeFragmentFromStack(){

    if (mFragmentManager.findFragmentById(R.id.fragment_container) instanceof FragmentHome) {
        exitFromApp();
    } else {
        mFragmentManager.popBackStackImmediate();

    }
}

答案 5 :(得分:1)

尝试以下代码,它对我有用。

    rootView.setFocusableInTouchMode(true);
    rootView.requestFocus();
    rootView.setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (event.getAction() == KeyEvent.ACTION_DOWN) {
                if (keyCode == KeyEvent.KEYCODE_BACK) {

                     final Intent startIntent = new Intent(context, MainActivity.class);
                     startIntent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                     startActivity(startIntent);
                     getActivity().finish();

            }
            }
            return false;
        }
    });
    return rootView;

答案 6 :(得分:-1)

在你的清单中试试这个 我认为它会对你有所帮助 &GT;

<application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".Frame1"
            android:label="@string/frame_1"
            android:parentActivityName=".MainActivity">
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="com.webservice.appname.MainActivity" />
        </activity>
        <activity
            android:name=".Frame2"
            android:label="@string/frame_2"
            android:parentActivityName=".MainActivity">
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="com.webservice.appname.MainActivity" />
        </activity>
        <activity
            android:name=".Frame3"
            android:label="@string/frame_3"
            android:parentActivityName=".MainActivity">
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="com.webservice.appname.MainActivity" />
        </activity>
        .
        .
        .
        .
        .
</application>