选择Tab并在其片段中运行代码

时间:2018-02-07 16:10:08

标签: android android-fragments

我有一个带有VeiwPager和MainActivity的标签设置。当一个特定的标签," B"选择我想要显示片段B用户界面并开始做某事。 我发现这样做的方法是在片段中使用LocalBroadcastReceiver" B"让它调用一个方法。广播是从onTabSelected方法内的Main Activity发送的。

这是一个好方法吗?

1 个答案:

答案 0 :(得分:0)

Activity.xml

<android.support.design.widget.TabLayout
    android:id="@+id/tabLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/colorPrimary"
    app:tabGravity="fill"
    app:tabMode="fixed" />

<android.support.v4.view.ViewPager
    android:id="@+id/viewPager"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

Activity.class

TabLayout tabLayout;
ViewPager viewPager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_tab);
    tabLayout = findViewById(R.id.tabLayout);
    viewPager = findViewById(R.id.viewPager);

    setUpviewPager();
    tabLayout.setupWithViewPager(viewPager);
}

private void setUpviewPager() {


    ViewPagerAdpater viewPagerAdapter = new ViewPagerAdpater(getSupportFragmentManager());
    viewPager.setAdapter(viewPagerAdapter);
}


private class ViewPagerAdpater extends FragmentPagerAdapter {


    ViewPagerAdpater(FragmentManager supportFragmentManager) {
        super(supportFragmentManager);
    }

    @Override
    public Fragment getItem(int position) {
        switch (position) {
            case 0:
                return new FirsFrag();

            case 1:
                return new FirsFrag();

            case 2:
                return new FirsFrag();

            default:
                return null;
        }
    }

    @Nullable
    @Override
    public CharSequence getPageTitle(int position) {
        switch (position) {
            case 0:
                return "First Tab";
            case 1:
                return "Second Tab";
            case 2:
                return "Third Tab";
            default:
                return "";
        }
    }

    @Override
    public int getCount() {
        return 3;
    }

    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
        return view == object;
    }
}



Thanks, just run this code, this adapter is FragmentPagerAdpater