how to handle back event in drawer list fragment in android activity

纵然是瞬间 提交于 2020-01-15 09:42:15

问题


I have developed an application that have one activity and in this activity there are add some fragment in drawer list item (side).So my issue is when I am open on any drawer fragment item and then pressed back button application going to close.So how to handle back event like 3 - 2 -1 when pressed back its open precious fragment.

Code of main activity

    public class MainActivity extends FragmentActivity {
    private DrawerLayout DrawerLayout;
    private ListView DrawerList;
    private ActionBarDrawerToggle DrawerToggle;

    private CharSequence DrawerTitle;

    private CharSequence Title;

    private String[] MenuTitles;
    private TypedArray MenuIcons;

    private DrawerListAdapter adapter;
    private ArrayList<DrawerItem> DrawerItems;

    @SuppressLint("NewApi")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Title = DrawerTitle = getTitle();

        MenuTitles = getResources().getStringArray(R.array.drawer_items);

        MenuIcons = getResources().obtainTypedArray(R.array.drawer_icons);

        DrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        DrawerList = (ListView) findViewById(R.id.list_slidermenu);

        DrawerItems = new ArrayList<DrawerItem>();

        DrawerItems.add(new DrawerItem(MenuTitles[0], MenuIcons.getResourceId(
                0, -1)));

        DrawerItems.add(new DrawerItem(MenuTitles[1], MenuIcons.getResourceId(
                1, -1)));

        DrawerItems.add(new DrawerItem(MenuTitles[2], MenuIcons.getResourceId(
                2, -1)));

        DrawerItems.add(new DrawerItem(MenuTitles[3], MenuIcons.getResourceId(
                3, -1)));

        DrawerItems.add(new DrawerItem(MenuTitles[4], MenuIcons.getResourceId(
                4, -1)));

        DrawerItems.add(new DrawerItem(MenuTitles[5], MenuIcons.getResourceId(
                5, -1)));

        DrawerItems.add(new DrawerItem(MenuTitles[6], MenuIcons.getResourceId(
                6, -1)));

        MenuIcons.recycle();

        DrawerList.setOnItemClickListener(new SlideMenuClickListener());

        adapter = new DrawerListAdapter(getApplicationContext(), DrawerItems);
        DrawerList.setAdapter(adapter);

        getActionBar().setDisplayHomeAsUpEnabled(true);
        getActionBar().setHomeButtonEnabled(true);

        DrawerToggle = new ActionBarDrawerToggle(this, DrawerLayout,
                R.drawable.ic_drawer, R.string.app_name, R.string.app_name) {
            public void onDrawerClosed(View view) {
                getActionBar().setTitle(Title);

                invalidateOptionsMenu();
            }

            public void onDrawerOpened(View drawerView) {
                getActionBar().setTitle(DrawerTitle);

                invalidateOptionsMenu();
            }
        };
        DrawerLayout.setDrawerListener(DrawerToggle);

        if (savedInstanceState == null) {

            displayView(0);
        }
    }

    private class SlideMenuClickListener implements
            ListView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                                long id) {

            displayView(position);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        if (DrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }

        switch (item.getItemId()) {
            case R.id.action_settings:
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {

        boolean drawerOpen = DrawerLayout.isDrawerOpen(DrawerList);
        menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
        return super.onPrepareOptionsMenu(menu);
    }

    @SuppressLint("NewApi")
    private void displayView(int position) {

        Fragment fragment = null;
        switch (position) {
            case 0:
                fragment = new Home_Activity();
                break;
            case 1:
                fragment = new Activity_two();
                break;
            case 2:
                fragment = new Activity_three();
                break;
            case 3:
                fragment = new Activity_four();
                break;
            case 4:
                fragment = new Activity_five();
                break;
            case 5:
                fragment = new Activity_six();
                break;
            case 6:
                fragment = new Activity_seven();
                break;

            default:
                break;



FragmentTransaction transaction = getFragmentManager().beginTransaction();
            transaction.replace(R.id.frame_container, fragment);
            transaction.addToBackStack(null);
            transaction.commit();
        }

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

            DrawerList.setItemChecked(position, true);
            DrawerList.setSelection(position);
            setTitle(MenuTitles[position]);
            DrawerLayout.closeDrawer(DrawerList);
        } else {

            Log.e("MainActivity", "Error in creating fragment");
        }
    }

    @SuppressLint("NewApi")
    @Override
    public void setTitle(CharSequence title) {
        Title = title;
        getActionBar().setTitle(Title);
    }

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

        DrawerToggle.syncState();
    }


one fragment code...

    public class Activiy_three extends Fragment {

    private GridView gallery;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View v = inflater.inflate(R.layout.activity_three_fragment,
                container, false);
        List<Item> Images = new ArrayList<Item>();
        //todo : develop as per date photo
        Images.add(new Item("Image 1", R.drawable.penguins));
        Images.add(new Item("Image 1", R.drawable.pulips));
        Images.add(new Item("Image 1", R.drawable.lighthouse));
        Images.add(new Item("Image 1", R.drawable.koala));
        Images.add(new Item("Image 1", R.drawable.jellyfish));
        Images.add(new Item("Image 1", R.drawable.hydrangeas));
        Images.add(new Item("Image 1", R.drawable.chrysanthemum));
        Images.add(new Item("Image 1", R.drawable.home));

        gallery = (GridView) v.findViewById(R.id.gridview);
        Global.photoAdapter = new PhotoAdapter(getActivity(), Images,false);
        gallery.setAdapter(Global.photoAdapter);

        gallery.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            public void onItemClick(AdapterView<?> parent, View view, int
                    position, long id) {

//                Intent i = new Intent(getActivity(), FullImageActivity.class);
//                i.putExtra(Global.Id, position);
//                startActivity(i);

                Fragment fragment = new FullImageActivity();
                FragmentManager fragmentManager = getFragmentManager();

                Bundle args = new Bundle();
                args.putInt(Global.Id, position);
                fragment.setArguments(args);

                fragmentManager.beginTransaction()
                        .replace(R.id.frame_container, fragment).commit();
            }
        });
        return v;
    }
}

回答1:


You need add the fragment to the backstack

FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, fragment);
transaction.addToBackStack(null);
transaction.commit();

And you can use popBackStack() to pop the fragment from the stack

http://developer.android.com/reference/android/app/FragmentManager.html#popBackStack()

Edit:

What you have

 default:
            break;

 FragmentTransaction transaction = getFragmentManager().beginTransaction();
        transaction.replace(R.id.frame_container, fragment);
        transaction.addToBackStack(null);
        transaction.commit();
    }

Should be

private void displayView(int position) {

    Fragment fragment = null;
    switch (position) {
        case 0:
            fragment = new Home_Activity();
            break;
        case 1:
            fragment = new Activity_two();
            break;
        case 2:
            fragment = new Activity_three();
            break;
        case 3:
            fragment = new Activity_four();
            break;
        case 4:
            fragment = new Activity_five();
            break;
        case 5:
            fragment = new Activity_six();
            break;
        case 6:
            fragment = new Activity_seven();
            break;

        default:
            break;

    }

    if (fragment != null) {
        FragmentTransaction transaction = getFragmentManager().beginTransaction();
        transaction.replace(R.id.frame_container, fragment);
        transaction.addToBackStack(null);
        transaction.commit();

        DrawerList.setItemChecked(position, true);
        DrawerList.setSelection(position);
        setTitle(MenuTitles[position]);
        DrawerLayout.closeDrawer(DrawerList);
    } else {

        Log.e("MainActivity", "Error in creating fragment");
    }
}



回答2:


You can use getName method of FragmentManager.BackStackEntry which is introduced in API level 14 with

FragmentManager.BackStackEntry backEntry=getFragmentManager().getBackStackEntryAt(getActivity().getFragmentManager().getBackStackEntryCount()-1);
String str=backEntry.getName();
Fragment fragment=getFragmentManager().findFragmentByTag(str);


来源:https://stackoverflow.com/questions/22550420/how-to-handle-back-event-in-drawer-list-fragment-in-android-activity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!