-1

I have implemented a navigation drawer for my fragment hence would like to know what's the best way to implement the back pressed feature for fragments only as well as where the code necessarily needs to go? I've used some back pressed code below but it doesn't work.

activity class

public class BakerlooHDNActivity extends AppCompatActivity {

    //save our header or result
    private Drawer result = null;

    private int getFactorColor(int color, float factor) {
        float[] hsv = new float[3];
        Color.colorToHSV(color, hsv);
        hsv[2] *= factor;
        color = Color.HSVToColor(hsv);
        return color;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bakerloo_hdn);



        LocalBroadcastManager.getInstance(this).registerReceiver(onNotice, new IntentFilter("BACKPRESSED_TAG"));


        final String actionBarColor = "#B36305";

        Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(mToolbar);

        if(getSupportActionBar()!=null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setDisplayShowHomeEnabled(false);
            getSupportActionBar().setTitle(Html.fromHtml("<font color='#FFFFFF'>" + getResources().getString(R.string.hdn) + "</font>"));

            final Drawable upArrow = ContextCompat.getDrawable(this, R.drawable.abc_ic_ab_back_mtrl_am_alpha);
            upArrow.setColorFilter(getResources().getColor(R.color.white), PorterDuff.Mode.SRC_ATOP);
            getSupportActionBar().setHomeAsUpIndicator(upArrow);
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            getWindow().setStatusBarColor(getFactorColor(Color.parseColor(actionBarColor), 0.8f));
        }

        // start of navigation drawer
        AccountHeader headerResult = new AccountHeaderBuilder()
            .withActivity(this)
            .withCompactStyle(true)
            .withHeaderBackground(R.color.bakerloo)
            .withProfileImagesVisible(false)
            .withTextColor(Color.parseColor("#FFFFFF"))
            .withSelectionListEnabled(false)

            .addProfiles(
                    new ProfileDrawerItem().withName(getString(R.string.hello)).withEmail(getString(R.string.world))
            )
            .build();

        result = new DrawerBuilder()
            .withActivity(this)
            .withAccountHeader(headerResult)
            .withTranslucentStatusBar(false)
            .withActionBarDrawerToggle(false)
            .withSelectedItem(-1)
            .addDrawerItems(
                    new SectionDrawerItem().withName(R.string.other_lines_nocaps).setDivider(false),
                    new PrimaryDrawerItem().withName(R.string.hello_world).withIdentifier(1).withCheckable(false)
            )
            .build();
        // end of navigation drawer
    }


    @Override
    public void onBackPressed() {
        if (result.isDrawerOpen()) {
            result.closeDrawer();
        } else {
            super.onBackPressed();
        }

        LocalBroadcastManager.getInstance(context).sendBroadcast(new Intent("BACKPRESSED_TAG"));
    }
}

fragment class

public class FragmentBakerlooHDN extends android.support.v4.app.Fragment {

    public FragmentBakerlooHDN() {
        // Required empty constructor
    }

    BroadcastReceiver onNotice = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            // do stuff when back in activity is pressed
             headerResult.closeDrawer();
        }
    };

    // Declaring navigation drawer
    private AccountHeader headerResult = null;
    private Drawer result = null;


    /**
     * Whether or not the activity is in two-pane mode, i.e. running on a tablet
     * device.
     */
    private boolean mTwoPane;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        LocalBroadcastManager.getInstance(getActivity()).registerReceiver(onNotice, new IntentFilter("BACKPRESSED_TAG"));

        super.onCreate(savedInstanceState);
    }

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_bakerloo_hdn, container, false);


        headerResult = new AccountHeaderBuilder()
                .withActivity(getActivity())
                .withCompactStyle(true)
                .withHeaderBackground(R.color.bakerloo)
                .withProfileImagesVisible(false)
                .withTextColor(Color.parseColor("#FFFFFF"))
                .withSelectionListEnabled(false)

                .addProfiles(
                        new ProfileDrawerItem().withName(getString(R.string.hdn)).withEmail(getString(R.string.hello_world))
                )
                .build();

        result = new DrawerBuilder()
                .withActivity(getActivity())
                .withAccountHeader(headerResult)
                .withTranslucentStatusBar(false)
                .withActionBarDrawerToggle(false)
                .withSelectedItem(-1)
                .addDrawerItems(
                new PrimaryDrawerItem().withName(R.string.hello_world).withIdentifier(1).withCheckable(false)
                )
                .build();


        super.onCreate(savedInstanceState);
        return v;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        View v = getView();

        super.onActivityCreated(savedInstanceState);
    }
}
wbk727
  • 8,017
  • 12
  • 61
  • 125

1 Answers1

1

There's no onBackPressed() in Fragment. It's Activity's method. What you can do, you can make your activity call your fragment method when its onBackPressed() is called:

@Override
public void onBackPressed() {
    if (!frag.onBackPressed() ) {
        super.onBackPressed();
    }
}

and then your fragment's onBackPressed() could do anything you want and returntruewhen it done anything, orfalse` otherwise, so you can call super's one in such case.

Marcin Orlowski
  • 72,056
  • 11
  • 123
  • 141
  • What do I replace `frag` with? – wbk727 Aug 05 '15 at 12:04
  • reference to fragment you want to notify about onBackPressed(). Most likely it will be your `FragmentHDN` fragment – Marcin Orlowski Aug 05 '15 at 12:05
  • Just tried it and it's not working. Please check latest screenshot – wbk727 Aug 05 '15 at 12:09
  • you do NOT have `onBackPressed()` in fragment, so `@Override` is incorrect. You need to add my code to your activity too. Have you done this? – Marcin Orlowski Aug 05 '15 at 12:18
  • First, stop posting text as images. That's annoying. Also you seem to lack java fundamentals. What you wrote will only work on static methods and this makes no use here. You need to find your fragment with `findFragmentById()` (or `.. ByTag()`) and then call method on the object you get – Marcin Orlowski Aug 05 '15 at 15:23
  • `findFragmentById()` does not appear when I try to type it in. Also does that exclamation mark need to be there? – wbk727 Aug 05 '15 at 17:14
  • Yes, `!` is negation. Are you calling `findFragmentById()` from FragmentManager? – Marcin Orlowski Aug 05 '15 at 17:27
  • No - can't really do that tbh because I'm replacing the detail fragment with a fragment for my master/detail app on tablets. – wbk727 Aug 05 '15 at 18:16
  • Code has been updated. The only problem I now have is closing the drawer, which doesn't happen but closes the fragment instead. Any idea what's missing from my updated code? – wbk727 Aug 05 '15 at 21:38