2

I want to have 3 tabs in an activity, each made up of a fragment (1, 2 & 3 respectively) having a RecyclerView in each fragment. On clicking an list item of the RecyclerView in any of the three tabs, I want to replace the corresponding fragment with another fragment (fragment 4) under the same tab along with preserving the action of back button to go back to the original fragment. How can I implement this?

My XML for the MainActivity is:

    <?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>

My Code for MainActivity is:

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);
    }
}

My OneFragment code is:

(check out 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();
            }
        }

    }

}

My XML for OneFragment is:

    <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 and ThreeFragment have very similar structure and code.

Abhilash Kishore
  • 1,933
  • 2
  • 13
  • 27

1 Answers1

1

Check out this answer https://stackoverflow.com/a/11974777/685292. It's an example how to implement simple back stacking with ViewPager by your own since addToBackStack(null) does not work for ViewPager fragments.

Community
  • 1
  • 1
Suraj Kumar Sau
  • 188
  • 2
  • 8