Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ANDROID: ViewPager with different Fragments in instantiateItem method

I use ViewPager to create fragments that swipe left and now I want insert fragments into each fragment page.

activityMain.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    ...
    android:orientation="vertical">

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

    <devlight.io.library.ntb.NavigationTabBar
        android:id="@+id/ntb_horizontal"
        app:ntb_swiped="true"/>


</android.support.design.widget.CoordinatorLayout>

and this: tab0_fragment.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="40dp"
        android:textSize="30sp"
        android:gravity="center"
        android:id="@+id/textView"
        android:layout_centerHorizontal="true"
        android:textColor="@android:color/holo_green_dark"
        android:text="Social\nFragment"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:autoLink="web"
        android:textSize="15sp"
        android:layout_marginTop="10dp"
        android:layout_centerHorizontal="true"
        android:text="androidbelieve.com"
        android:textColor="#000"
        android:layout_below="@+id/textView"
        android:textStyle="italic"/>

</RelativeLayout>

I have a ViewPager in mainActivity.java

final ViewPager viewPager = (ViewPager) findViewById(R.id.myviewpager);
viewPager.setAdapter(new PagerAdapter() {
...

...
}

I try open one screen in viewpager via fragment layout.

I try this:

final ViewPager viewPager = (ViewPager) findViewById(R.id.myviewpager);
viewPager.setAdapter(new PagerAdapter() {
    ...
    public Object instantiateItem(final ViewGroup container, final int position) {
           if (position == 0)
           {
                final View view = LayoutInflater.from(getBaseContext()).inflate(R.layout.fragment_tab0, null, false);
                FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
                fragmentTransaction.replace(R.id.myviewpager,new tab0Fragment()).commit();
                container.addView(view);
                return view;
           }
           else if (position == 1)
           ...

   } 

...
}

AND tab0Fragment.java

public class tab0Fragment extends Fragment {

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_tab0,null);
    }
}

I am noob in android. how can correct this code?


Solution: The answers was not my answer but that help me a lot.

According @Mr. Rabbit ans @Amit Upadhyay I change top code to this:

@Override
            public Object instantiateItem(final ViewGroup container, final int position) {

                if (position == 0)
                {
                    final View view = LayoutInflater.from(getBaseContext()).inflate(R.layout.fragment_tab0, null, false);
                    MyAdapter adapter = new MyAdapter(getSupportFragmentManager());
                    adapter.addFragment(new tab0Fragment(), getResources().getString(R.string.tab0));
                    container.addView(view);
                    return view;
                }
                else if (position == 1)
                {

and also adding MyAdapter class according @Mr. Rabbit's answer.

hope help someone else.

like image 357
elma Avatar asked Oct 18 '22 17:10

elma


2 Answers

Try to separate out your adapter and below code.

MyAdapter.java

public class MyAdapter extends FragmentPagerAdapter{

    private final List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitleList = new ArrayList<>();

    public MyAdapter(FragmentManager fm) {
        super(fm);
    }

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

Create your Fragments

FragmentOne.java

public class FragmentOne extends Fragment {
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState)    {
      View  view = inflater.inflate(R.layout.fragment_one, container, false);
        return view;
    }
}

FragmentTwo.java

public class FragmentTwo extends Fragment {
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState)    {
     View  view = inflater.inflate(R.layout.fragment_two, container, false);
        return view;
    }
}

Setup your viewpager like this in your activity.

final ViewPager viewPager = (ViewPager) findViewById(R.id.myviewpager);
    MyAdapter adapter = new MyAdapter(getSupportFragmentManager());

    // Add your fragments in adapter.
    FragmentOne fragmentOne = new FragmentOne();
    adapter.addFragment(fragmentOne, getResources().getString(R.string.fragment_one_title));

    FragmentTwo fragmentTwo = new FragmentTwo();
    adapter.addFragment(fragmentTwo, getResources().getString(R.string.fragment_two_title));

    viewPager.setAdapter(adapter);

Then finally set your NavigationTabBar with your ViewPager.

final NavigationTabBar navigationTabBar = (NavigationTabBar) findViewById(R.id.ntb_horizontal);
navigationTabBar.setViewPager(viewPager, 2);
like image 125
phoenix Avatar answered Oct 21 '22 03:10

phoenix


To achieve this you can create a custom ViewPagerAdapter. Eg:

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

import java.util.ArrayList;

/**
 * Created by aupadhyay on 1/5/17.
 */

public class ViewPagerAdapter extends FragmentPagerAdapter {

    ArrayList<Fragment> fragments = new ArrayList<>();
    ArrayList<String> tabTitles = new ArrayList<>();

    public void addFragments(Fragment fragment, String tabTitle)
    {
        this.fragments.add(fragment);
        this.tabTitles.add(tabTitle);
    }

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

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

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

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

}

Now you can set adapter on viewpager like this:

final ViewPager viewPager = (ViewPager) findViewById(R.id.myviewpager);

ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());

        viewPagerAdapter.addFragments(new Tab0Fragment(), "First");
        viewPagerAdapter.addFragments(new Tab1Fragment(), "Second");
        viewPagerAdapter.addFragments(new Tab2Fragment(), "Third");
        // add more if required.

viewPager.setAdapter(viewPagerAdapter);

Tab0Fragment, Tab1Fragment, Tab1Fragment are the fragments created by you to add in your viewpager.

like image 30
Amit Upadhyay Avatar answered Oct 21 '22 05:10

Amit Upadhyay