0

I have a ViewPager with three fragments, and I want to replace the third fragment with another one, I checked the post about it, but nothing works, my previous layout is still displayed and the new one just appear over it . Please give me a hint, thanks a lot. Here is my HomeFragment :

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_home, container, false);

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

    tabLayout = (TabLayout) rootView.findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(viewPager);
    setupTabIcons();
    // Inflate the layout for this fragment
    return rootView;
}
private void setupTabIcons() {
    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(getFragmentManager());
    adapter.addFragment(new ChatActivity(), "Chat");
    adapter.addFragment(new MapaActivity(), "Mapa");

    adapter.addFragment(new WebServiceActivity(), "Form");

    viewPager.setAdapter(adapter);
}

class ViewPagerAdapter extends FragmentStatePagerAdapter {
    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);
    }

    @Override
    public int getItemPosition(Object object){
        return PagerAdapter.POSITION_NONE;
    }
}

the layout fragment_home.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.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>

the webServiceActivity onCreateView method:

 @Override
 public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.activity_web_service, container, false);
        manager= getFragmentManager();
        //creacion de spinner
        Spinner spinner = (Spinner) rootView.findViewById(R.id.spinner);
        // Create an ArrayAdapter using the string array and a default spinner layout
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity().getBaseContext(),
                R.array.categorias_array, android.R.layout.simple_spinner_item);   adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
        spinner.setAdapter(adapter);
        b = (Button) rootView.findViewById(R.id.button1);
        // btnPosicion = (Button) rootView.findViewById(R.id.boton_posicion);
        b.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // fragmento a insertar
                OneFragment formTurismo = new OneFragment();
                FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
// and add the transaction to the back stackx`
                transaction.replace(R.id.selector_forms, formTurismo,"Turismo");                transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
                transaction.addToBackStack(null);
                transaction.commit();
            }
        });
        return rootView;
    }

the activity_web_service.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"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:id="@+id/selector_forms"
    >
    <TextView
        android:id="@+id/textView1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:gravity="center"
        android:text="@string/formulario"
        android:textSize="30dp" />
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:id="@+id/switch_layout"
        android:orientation="vertical">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="40dp"
            android:text="@string/txt_categorias"
            android:id="@+id/loginUsernameText"
            android:layout_gravity="center_horizontal"
            android:textSize="20sp"/>
    <Spinner
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:id="@+id/spinner"
        android:layout_below="@id/textView1"
        android:padding="10dp"
        android:layout_marginLeft="30dp"
        android:layout_marginRight="30dp" />
    <Button
        android:id="@+id/button1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:padding="10dp"
        android:layout_marginLeft="30dp"
        android:layout_marginRight="30dp"
        android:layout_marginTop="8dp"
        android:text="Ver formulario" />
    </LinearLayout>
</RelativeLayout>

the fragment_one.xml

<?xml version="1.0" encoding="utf-8"?>
<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"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:id="@+id/turismo_form"
    >
    <TextView
        android:id="@+id/textView1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:gravity="center"
        android:text="@string/formularioT"
        android:textSize="30dp" />
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:orientation="vertical">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="40dp"
            android:text="@string/txt_canton"
            android:id="@+id/labelCantonT"
            android:layout_gravity="center_horizontal"
            android:textSize="20sp"/>
        <Spinner
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="8dp"
            android:id="@+id/spinner"
            android:padding="10dp"
            android:layout_marginLeft="30dp"
            android:layout_marginRight="30dp" />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="30dp"
            android:text="@string/txt_tipo"
            android:id="@+id/labelTipo"
            android:layout_gravity="center_horizontal"
            android:textSize="20sp"/>
        <Spinner
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="8dp"
            android:id="@+id/spinnerT"
            android:padding="10dp"
            android:layout_marginLeft="30dp"
            android:layout_marginRight="30dp" />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="40dp"
            android:text="@string/txt_nombreT"
            android:id="@+id/labelNombreT"
            android:layout_gravity="center_horizontal"
            android:textSize="20sp"/>
        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/nombreT"
            android:layout_gravity="center_horizontal"
            android:padding="10dp"
            android:layout_marginLeft="30dp"
            android:layout_marginRight="30dp"/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="40dp"
            android:text="@string/txt_direccionT"
            android:id="@+id/labelDireccionT"
            android:layout_gravity="center_horizontal"
            android:textSize="20sp"/>
        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/direccionT"
            android:layout_gravity="center_horizontal"
            android:padding="10dp"
            android:layout_marginLeft="30dp"
            android:layout_marginRight="30dp"/>
        <Button
            android:id="@+id/button1"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:padding="10dp"
            android:layout_marginLeft="30dp"
            android:layout_marginRight="30dp"
            android:layout_marginTop="8dp"
            android:text="Registrar" />
    </LinearLayout>
</RelativeLayout>
Paul
  • 93
  • 3
  • 16

2 Answers2

1

If you want to replace a fragment in your viewpager, you have to notify your adapter of the change. Your list of fragments needs to be updated to remove the 3rd fragment and add a new one in its place. After you've done that, you call notifyDataSetChanged in your adapter.

You could have an API like this in your adapter:

public void replaceFragment(Fragment fragment, String title, int index) {
    mFragmentList.remove(index);
    mFragmentList.add(index, fragment);
    // do the same for the title
    notifyDataSetChanged();
}
Francesc
  • 13,308
  • 4
  • 34
  • 50
  • Thanks a lot for the quickly reply, I add the method into my innerclass as you suggest, and change to static class ViewPageAdapter, also in my onClickListener make the call like this: OneFragment formTurismo = new OneFragment(); ViewPagerAdapter adapter = new ViewPagerAdapter(getFragmentManager()); adapter.replaceFragment(formTurismo,"Turismo",0); But launch this error : java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0 – Paul Mar 02 '16 at 23:51
  • I'm not sure what you are trying to say, but you pasted an exception here. You must be calling replaceFragment before you have added any fragments, as the exception is telling you that the list is empty. – Francesc Mar 02 '16 at 23:55
  • I trying to launch in the OnclickListener method of the button of the layout that I want to change is this ok or I making wrong ? – Paul Mar 03 '16 at 00:02
  • You do not have to create a new adapter when you want to replace a fragment. You use the existing adapter and call the API to replace one of the fragments with the new one. – Francesc Mar 03 '16 at 00:03
  • Ok, it's clear now, but sorry for the silly question but how i get the current adapter, in the other layout – Paul Mar 03 '16 at 00:23
  • If you have separate activities, you can't. You'll have to pass information from one activity to the other, maybe using startActivityForResult and setResult, or using an EventBus. – Francesc Mar 03 '16 at 00:37
-1

After reading the android documentation about the Viewpager I modify the activity_webservice.xml content to a framelayout and load dynamically the content using this code in onCreateMethod:

 manager= getFragmentManager();
        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        SelectorFragment fragment = new SelectorFragment();
        fragmentTransaction.add(R.id.selector_forms, fragment);
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.commit();

It call another xml layout called fragment_selector.xml, and inside the fragment class I add this:

 FragmentTransaction transaction = getFragmentManager().beginTransaction();
                transaction.replace(R.id.selector_forms, formulario);
                transaction.addToBackStack(null);

And it's done.

Paul
  • 93
  • 3
  • 16