Skip to content Skip to sidebar Skip to footer

How Can I Launch Fragment In Broadcast Receiver

How can I use broadcast receiver to start/lunch fragment for example : if I need to start/luanch activity , I can use intent : public void onReceive(final Context context, Intent i

Solution 1:

You must luanch intent and putextera and sendactivity. Then you can launch fragment from activity.

Solution 2:

Fragment is a part of Activity. Without Activity you cannot launch a separate Fragment. You can launch an Activity with Fragment.

One way is to create BroadcastReceiver inner class in Activity to launch Fragment.

Solution 3:

Does this work? Put this in your Broadcast Receiver:

activityIntent = newIntent(context, MainActivity.class);
activityIntent.putExtra("fragment", "fragment2");
activityIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(activityIntent);

and beneath the code you use to set your fragment pager adapter:

Bundlebundle= getIntent().getExtras();
if (bundle != null) {
    if (bundle.getString("fragment") != null) {
        /*Log.w(getClass().toString(), bundle.getString("fragment"));*/
        viewPager.setCurrentItem(2);
    }
}

This code is usually below something like this:

finalViewPagerviewPager= (ViewPager) findViewById(R.id.pager);
        finalPagerAdapteradapter=newFragmentPagerAdapter
                (getSupportFragmentManager(), tabLayout.getTabCount());
        viewPager.setAdapter(adapter);
        viewPager.addOnPageChangeListener(newTabLayout.TabLayoutOnPageChangeListener(tabLayout));
        tabLayout.setOnTabSelectedListener(newTabLayout.OnTabSelectedListener() {
            @OverridepublicvoidonTabSelected(TabLayout.Tab tab) {
                viewPager.setCurrentItem(tab.getPosition());
            }

            @OverridepublicvoidonTabUnselected(TabLayout.Tab tab) {

            }

            @OverridepublicvoidonTabReselected(TabLayout.Tab tab) {

            }

        });

Just make sure it's beneath where you set your adapter, and not just your viewpager, or else you won't be able to navigate to any fragments via the viewpager.

Post a Comment for "How Can I Launch Fragment In Broadcast Receiver"