简体   繁体   中英

Dynamically replace fragment when using tablayout and viewpager in android

I have struggled in the past couple of days to find the solution to this problem: I have one activity which contains a tab layout and a view pager. The view pager is filled with fragments using an adapter. Tabs are created with this viewpager and are fixed. My question is how can I change the layout of tabs dynamically (for example after a button click) ?

This is xml file

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        android:theme="@style/ThemeOverlay.AppCompat.Dark" />
    <android.support.design.widget.TabLayout
        android:id="@+id/tablayout"
        android:layout_width="match_parent"
        android:layout_height="65dp"
        android:background="@color/white"
        app:tabMode="fixed"
        app:tabGravity="fill"
        android:theme="@style/ThemeOverlay.AppCompat.Dark" />

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"/>
</LinearLayout>

This is Activity :

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    setupToolbar();

    viewPager = (ViewPager) findViewById(R.id.viewpager);
    setupViewPager(viewPager);

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tablayout);
    setupTabLayout(tabLayout);
}

private void setupToolbar(){
   ...
}


public void setupViewPager(ViewPager viewPager) {
    pageAdapter = new FragmentPageAdapter(getApplicationContext(), getSupportFragmentManager());
    pageAdapter.addFragment(ContentFragment.newInstance(), "Following", R.drawable.following);
    pageAdapter.addFragment(ContentFragment.newInstance(), "Discover", R.drawable.flower);
    pageAdapter.addFragment(ContentFragment.newInstance(), "", R.drawable.camera);
    pageAdapter.addFragment(ProfileFragment.newInstance(), "Profile", R.drawable.profile);
    pageAdapter.addFragment(ContentFragment.newInstance(), "Task List", R.drawable.list);
    viewPager.setAdapter(pageAdapter);
}

public void setupTabLayout(TabLayout tabLayout) {
    try {
        tabLayout.setupWithViewPager(viewPager);
        for (int i = 0; i < tabLayout.getTabCount(); i++) {
            TabLayout.Tab tab = tabLayout.getTabAt(i);
            tab.setCustomView(pageAdapter.getTabView(i));
        }
        tabLayout.requestFocus();
    }
    catch(Exception ex){
        Log.e("errr2", ex.getMessage());
    }
}

This is adapter :

public class FragmentPageAdapter extends FragmentStatePagerAdapter {
    private Context mContext;
private List<Fragment> mFragments = new ArrayList<>();
private List<String> mFragmentTitles = new ArrayList<>();
private List<Integer> mFragmentIcons = new ArrayList<>();

public FragmentPageAdapter(Context context, FragmentManager fm) {
    super(fm);
    this.mContext = context;
}

public void addFragment(Fragment fragment, String title, int drawable) {
    mFragments.add(fragment);
    mFragmentTitles.add(title);
    mFragmentIcons.add(drawable);
}



@Override
public Fragment getItem(int position) {

    return mFragments.get(position);
}


@Override
public int getItemPosition(Object object)
{
    return POSITION_UNCHANGED;
}

@Override
public int getCount() {
    return mFragments.size();
}

@Override
public CharSequence getPageTitle(int position) {
    return mFragmentTitles.get(position);
}

public View getTabView(int position) {
    View tab = LayoutInflater.from(mContext).inflate(R.layout.tabbar_view, null);
    TextView tabText = (TextView) tab.findViewById(R.id.tabText);
    ImageView tabImage = (ImageView) tab.findViewById(R.id.tabImage);
    tabText.setText(mFragmentTitles.get(position));
    tabImage.setBackgroundResource(mFragmentIcons.get(position));
    if (position == 3) {
        tab.setSelected(true);
    }
    return tab;
}

}

The normal way to replace a fragment is by calling

  fragmentManager.beginTransaction().replace(placeholderId, editPrifileFragment).commit();

but what should I use for placeholderId in this case ? because in activity layout I don't have a placeholder for fragments, just a viewpager. So how can I replace the fragment dynamically and also keep the back button functionality ? I have searched a lot and found some hacky solutions , but I think this is a very common situation and should have a better solution. thanks.

Your ViewPager Fragment should hold the placeholderId . So in your Fragment (which is part of the ViewPager ) you can call getChildFragmentManager() to add Fragment like you usually do.

childFragmentManager.beginTransaction().add(placeholderId, editPrifileFragment).addToBackStack(null).commit();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM