动态更改TabLayout内的片段

时间:2016-01-12 17:27:28

标签: android android-fragments android-tablayout

我希望活动中有3个标签,每个标签由一个片段(分别为1,2和3)组成,每个片段中都有RecyclerView。在单击三个选项卡中任意一个的RecyclerView列表项时,我想用相同选项卡下的另一个片段(片段4)替换相应的片段,同时保留后退按钮的操作以返回到原始片段。我该如何实现呢?

我的MainActivity XML是:

    <?xml version="1.0" encoding="utf-8"?>

    <android.support.design.widget.CoordinatorLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|enterAlways"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

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

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"  />
</android.support.design.widget.CoordinatorLayout>

我的MainActivity代码是:

public class MainActivity extends AppCompatActivity {

private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private int[] tabIcons = {
        R.drawable.ic_tab_favourite,
        R.drawable.ic_tab_call,
        R.drawable.ic_tab_contacts
};

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

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

    getSupportActionBar().setDisplayHomeAsUpEnabled(false);
    /*getSupportActionBar().hide();*/

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

    tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(viewPager);
    /*setupTabIcons();*/
}

/*private void setupTabIcons() throws NullPointerException{
    tabLayout.getTabAt(0).setIcon(tabIcons[0]);
    tabLayout.getTabAt(1).setIcon(tabIcons[1]);
    tabLayout.getTabAt(2).setIcon(tabIcons[2]);
}*/

private void setupViewPager(ViewPager viewPager) {
    ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
    adapter.addFragment(new OneFragment(), "Events");
    adapter.addFragment(new TwoFragment(), "Schedule");
    adapter.addFragment(new ThreeFragment(), "Register");
    viewPager.setAdapter(adapter);
}

class ViewPagerAdapter extends FragmentPagerAdapter {
    private final List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitleList = new ArrayList<>();

    public ViewPagerAdapter(FragmentManager manager) {
        super(manager);
    }

    @Override
    public Fragment getItem(int position) {
        return mFragmentList.get(position);
    }

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

    public void addFragment(Fragment fragment, String title) {
        mFragmentList.add(fragment);
        mFragmentTitleList.add(title);
    }

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

我的OneFragment代码是:

(查看recyclerView.addOnItemTouchListener)

    public class OneFragment extends android.support.v4.app.Fragment
{
    public TextView name;
    public ImageView imgViewIcon;
    public CardView cardView;

    public OneFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View root = inflater.inflate(R.layout.fragment_one, container, false);
        RecyclerView recyclerView = (RecyclerView) root.findViewById(R.id.recyclerView);
        final List<ItemData> nitemsData = new ArrayList<ItemData>();
        nitemsData.add( new ItemData("Literature",R.mipmap.ic_launcher));
        nitemsData.add( new ItemData("Art",R.mipmap.ic_launcher));
        nitemsData.add(new ItemData("Music", R.mipmap.ic_launcher));
        nitemsData.add( new ItemData("Theatre",R.mipmap.ic_launcher));
        nitemsData.add( new ItemData("Dance",R.mipmap.ic_launcher));
        nitemsData.add( new ItemData("Udbhav Cup",R.mipmap.ic_launcher));
        nitemsData.add(new ItemData("Misc", R.mipmap.ic_launcher));


        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        MyAdapter mAdapter = new MyAdapter(nitemsData);
        recyclerView.setAdapter(mAdapter);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.addOnItemTouchListener(
                new RecyclerItemClickListener(getActivity(), new RecyclerItemClickListener.OnItemClickListener() {
                    @Override public void onItemClick(View view, int position) {



                        //How to replace OneFragment with another fragment, say FourFragment, under the same tab? 
                        //Also, hitting the back button should take me back to OneFragment




                    }
                })
        );
        return root;

    }

    public void item_remove(List<ItemData> nitemsData,String att){
        Iterator<ItemData> itr = nitemsData.iterator();
        while (itr.hasNext()) {
            ItemData nitem = itr.next();

            if (nitem.getTitle().equals(att))
            {
                itr.remove();
            }
        }

    }

}

我的OneFragment XML是:

    <RelativeLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.msrit.abhilash.udbhavtake1.OneFragment">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="ONE"
        android:visibility="gone"
        android:textSize="40dp"
        android:textStyle="bold"
        android:layout_centerInParent="true"/>

    <android.support.v7.widget.RecyclerView
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".OneFragment"
        android:clipToPadding="false"
        />
</RelativeLayout>

TwoFragment和ThreeFragment具有非常相似的结构和代码。

1 个答案:

答案 0 :(得分:1)

查看此答案https://stackoverflow.com/a/11974777/685292。这是一个如何使用ViewPager实现简单的后向堆叠的示例,因为addToBackStack(null)对ViewPager片段不起作用。