How can I launch fragment in broadcast receiver

前端 未结 3 851
旧巷少年郎
旧巷少年郎 2020-12-21 22:36

How can I use broadcast receiver to start/lunch fragment for example : if I need to start/luanch activity , I can use intent :



        
相关标签:
3条回答
  • 2020-12-21 23:06

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

    0 讨论(0)
  • 2020-12-21 23:20

    Does this work? Put this in your Broadcast Receiver:

    activityIntent = new Intent(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:

    Bundle bundle = 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:

            final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
            final PagerAdapter adapter = new FragmentPagerAdapter
                    (getSupportFragmentManager(), tabLayout.getTabCount());
            viewPager.setAdapter(adapter);
            viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
            tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
                @Override
                public void onTabSelected(TabLayout.Tab tab) {
                    viewPager.setCurrentItem(tab.getPosition());
                }
    
                @Override
                public void onTabUnselected(TabLayout.Tab tab) {
    
                }
    
                @Override
                public void onTabReselected(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.

    0 讨论(0)
  • 2020-12-21 23:26

    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.

    0 讨论(0)
提交回复
热议问题