返回按片段

时间:2014-06-18 04:34:32

标签: android android-fragments slidingmenu

我在我的应用中使用滑动菜单并从MainActivity启动片段 我想在按下后退按钮时关闭应用程序。 当它在最后一个片段中按下后退按钮时它打开活动但是我想在最后片段中按下后退按钮时退出应用程序。我怎么能这样做。

这是我在创作

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
    getActionBar().setDisplayHomeAsUpEnabled(true);
    getActionBar().setHomeButtonEnabled(true);
    getActionBar().setBackgroundDrawable(
            new ColorDrawable(Color.parseColor("#0057b3")));

    setContentView(R.layout.activity_main);
    graphicUtil = new GraphicsUtil();

    mTitle = mDrawerTitle = getTitle();
    navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
    navMenuIcons = getResources()
            .obtainTypedArray(R.array.nav_drawer_icons);

    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);

    mDrawerList = (ListView) findViewById(R.id.list_slidermenu);

    navDrawerItems = new ArrayList<NavDrawerItem>();
    // My Feeds
    navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons
            .getResourceId(0, -1)));
    // Private Feeds
    navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons
            .getResourceId(1, -1)));
    // My Profile
    navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons
            .getResourceId(2, -1)));
    // People and Groups
    navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons
            .getResourceId(3, -1)));
    // Messages
    navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons
            .getResourceId(4, -1)));
    // Favorites
    navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons
            .getResourceId(5, -1)));
    // Credits
    navDrawerItems.add(new NavDrawerItem(navMenuTitles[6], navMenuIcons
            .getResourceId(6, -1)));
    // Settings
    navDrawerItems.add(new NavDrawerItem(navMenuTitles[7], navMenuIcons
            .getResourceId(7, -1)));
    // About this app
    navDrawerItems.add(new NavDrawerItem(navMenuTitles[8], navMenuIcons
            .getResourceId(8, -1)));
    // Contact us
    navDrawerItems.add(new NavDrawerItem(navMenuTitles[9], navMenuIcons
            .getResourceId(9, -1)));
    // Log Out
    navDrawerItems.add(new NavDrawerItem(navMenuTitles[10], navMenuIcons
            .getResourceId(10, -1)));

    navMenuIcons.recycle();

    mDrawerList.setOnItemClickListener(new SlideMenuClickListener());

    adapter = new NavDrawerListAdapter(getApplicationContext(),
            navDrawerItems);
    mDrawerList.setAdapter(adapter);

    mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
            R.drawable.ic_drawer, R.string.app_name, R.string.app_name) {
        public void onDrawerClosed(View view) {
            getActionBar().setTitle(mTitle);
            invalidateOptionsMenu();
        }

        public void onDrawerOpened(View drawerView) {
            getActionBar().setTitle(mDrawerTitle);
            invalidateOptionsMenu();
        }
    };
    mDrawerLayout.setDrawerListener(mDrawerToggle);


    // open default fragment

    if (savedInstanceState == null) {
        displayView(0);
    }
}

这是我打开片段的显示视图方法

private void displayView(int position) {
    switch (position) {
    case 0:
        // fragment = new MyPublicPostsFragment();
        fragment = new MyFeedsFragment();
        break;
    case 1:
        fragment = new MyPrivatePostsFragment();
        break;
    case 2:
        fragment = new MyProfileFragment();
        break;
    case 3:
        fragment = new PeopleFragment();
        break;
    case 4:
        fragment = new MessagesFragment();
        break;
    case 5:
        fragment = new FavouritesFragment();
        break;
    case 6:
        fragment = new CreditsFragment();
        break;
    case 7:
        fragment = new SettingsFragment();
        break;
    case 8:
        fragment = new AboutThisAppFragment();
        break;
    case 9:
        fragment = new ContactUsFragment();
        break;
    case 10:
        fragment = new LogOutFragment();
        store.setLoginStatus(null);
        break;
    default:
        break;
    }

    if (fragment != null) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction()
                .replace(R.id.frame_container, fragment)
                .addToBackStack(null).commit();

        mDrawerList.setItemChecked(position, true);
        mDrawerList.setSelection(position);
        setTitle(navMenuTitles[position]);
        mDrawerLayout.closeDrawer(mDrawerList);

    } else {
        Log.e("Main Activity", "error in creating fragment");
    }}

任何帮助将不胜感激

提前完成

3 个答案:

答案 0 :(得分:1)

从此处删除addToBackStack():.addToBackStack(null).commit();

http://developer.android.com/reference/android/app/FragmentTransaction.html#addToBackStack(java.lang.String)

答案 1 :(得分:0)

将以下代码放在MainActivity()。java

    @Override
public void onBackPressed()
{
    // Do Here what ever you want do on back press;
    finish();
}

答案 2 :(得分:0)

有几种方法可以做到这一点(有些方法比其他方式更好):

  • 方法1:使用TAG字符串执行片段事务。这样在MainActivity的onBackPressed()中,您可以使用findFragmentByTag检查当前片段是什么,如果是要退出的片段,则退出,如果不执行任何操作。

  • 方式2:由于您的displayView方法正在使用切换,您可以在MainActivity中存储整数位置,这样在onBackPressed()中您可以检查整数是什么,因此您可以知道什么是片段。

  • 方式3:您还可以创建一个名为mCurrentFragment的变量来存储当前片段,在onBackPressed()中您可以使用instanceOf检查哪个片段,并应用它逻辑。

  • 方式4:您可以创建片段必须实现的侦听器,并在调用onBackPressed时,然后调用侦听器并执行您需要执行的操作。

如果您需要代码示例,请告诉我,我会很乐意添加它。

编辑1:

请记住,这是伪代码,它可能包含任何拼写错误或其他内容,请使用编译器正确检查。

在您的MainActivity.java中:

public class MainActivity extends FragmentActivity {

   // Code... 

   private Fragment mCurrentFragment;

   // Code...

   private void displayView(int position) {
      switch (position) {
         case 0:
           mCurrentFragment = new MyFeedsFragment();
           break;
         // Substitute fragment for mCurrentFragment in the rest of the method...
   }

  @Override
  public void onBackPressed() {
      if (mCurrentFragment instanceof LogOutFragment) {
        finish();
      } else {
         // Do whatever you want to do if necessary
      }
  }

}