androidandroid-fragmentsandroid-fragmentactivityslidingmenu

Use Activities instead of Fragments in a Sliding Menu


I have a sliding menu with some Fragments, but i want to change it with Activities, is it possible?

private void replaceFragment(int pos) {
    Fragment fragment = null;
    switch (pos) {
        case 0:
            fragment = new X();
            break;
        case 1:
            fragment = new Y();
            break;
        case 2:
            fragment = new Z();
            break;
        default:
            fragment = new X();
            break;
    }

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

I don't know how to change the last part of the code. --> FragmentManager and --> FragmentTransaction. Thanks!!


Solution

  • Yes you can use Activity in place of fragment, But you have following challenges.

    1. You need to implement sliding drawer on every activity, if you uses fragment then HomeActivity sliding drawer will be shown on all fragment

    update your code like this if you want to implement activity

    private void replaceFragment(int pos) {
        Intent intent = null;
        Context context = this;
        switch (pos) {
            case 0:
                intent = new Intent(context, SecondActivity.class);
                break;
            case 1:
                intent = new Intent(context, ThirdActivity.class);
                break;
            case 2:
                intent =  new Intent(context, FourthActivity.class);
                break;
            default:
                intent = new Intent(context, DefaultActivity.class);
                break;
        }
    
        if (intent != null) {
            startActivity(intent);
        }
    }