ViewPager的内容消失

ViewPager的内容消失

本文介绍了更改片段后,ViewPager的内容消失的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我带着一个新问题回到这里.因此,目前我创建了一个应用程序,当您单击按钮时,它可以从一个片段切换到另一个片段.在这2个片段中,有2个viewPagers,它们创建了自定义数量的按钮.但是问题是,当我从一个片段切换到另一个片段,然后又切换回来时,第一个片段的内容不再在这里.我尝试了很多事情,没有任何真正的帮助.我希望你能帮助我.预先感谢.

i'm back here with a new Question. So at the moment i created an app , that can switch from a fragment to another fragment when you click on a button. And inside those 2 fragments there is 2 viewPagers, whose create a custom number of buttons. But the problem is that when i switch from a fragment to the other one, and then i switch back , the content of the first one is no longer here. I tried a lot of things and nothing really help me. And i hope you can help me. Thanks in advance.

主要活动:

public class MainActivity extends AppCompatActivity {

    String identifiant=null;
    BottomBar bottombar;
    ProgressBar progressBar;
    ImageButton imageButton;
    TextView nomson;
    RelativeLayout aaaa;
    FragmentWhizz fragmentWhizz;
    FragmentPlaylist fragmentPlaylist;

    FragmentManager fm;


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

        setContentView(R.layout.activity_main);
        autorisation();


        fragmentWhizz = new FragmentWhizz();
        fragmentPlaylist=new FragmentPlaylist();

        Fragment fragment = new FragmentConnexion();
        FragmentManager fm = getFragmentManager();
        FragmentTransaction transaction = fm.beginTransaction();
        transaction.replace(R.id.contentFragment, fragment);
        transaction.commit();

        bottombar = (BottomBar) findViewById(bottomBar);

        aaaa = (RelativeLayout) findViewById(R.id.aaaa);


        bottombar.setVisibility(View.INVISIBLE);
        bottombar.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelected(@IdRes int tabId) {
                if (tabId == R.id.tab_whiz) {
                    if(identifiant !=null){
                        changementFragment(fragmentWhizz);
                    }
                }
                if (tabId == R.id.tab_playlist) {
                    if(identifiant !=null){
                        changementFragment(fragmentPlaylist);
                    }
                }
                if (tabId == R.id.tab_reveil) {
                    if(identifiant !=null){
                        changementFragment(new FragmentReveil());
                    }
                }
                if (tabId == R.id.tab_param) {
                    if(identifiant !=null){
                        changementFragment(new FragmentParam());
                    }
                }
            }
        });

    }
    public void changementFragment(final Fragment fragment){
        runOnUiThread(new Runnable() {
            public void run() {
                 fm = getFragmentManager();
                 FragmentTransaction ft =fm.beginTransaction();
                 ft.setCustomAnimations(android.R.animator.fade_in,android.R.animator.fade_out);
                 ft.replace(R.id.contentFragment, fragment).commit();
            }
        });
    }
}

具有ViewPager的2个片段之一:

One of the 2 fragments that have the ViewPager:

public class FragmentPlaylist extends Fragment {

    SlideToutesPlaylist fragmentAllPlaylist = new SlideToutesPlaylist();
    SlideUserPlaylist fragmentUserPlaylist = new SlideUserPlaylist();
    ViewPager mViewPager;
    FloatingActionButton floatbutton;
    private FragmentActivity myContext;

    @Override
    public void onAttach(Activity activity) {
        myContext=(FragmentActivity) activity;
        super.onAttach(activity);
    }

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(true);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View myView = inflater.inflate(R.layout.playlist, container, false);
        DeplacerBoutton deplacer = new DeplacerBoutton(getActivity(),2);
        floatbutton = (FloatingActionButton) myView.findViewById(R.id.floatingActionButton);
        floatbutton.setOnTouchListener(deplacer);
        mViewPager = (ViewPager) myView.findViewById(R.id.slide);
        mViewPager.setAdapter(new SamplePagerAdapter(myContext.getSupportFragmentManager()));
        Log.i("test","test");
        return myView;
    }


    public class SamplePagerAdapter extends FragmentStatePagerAdapter {

        SamplePagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public android.support.v4.app.Fragment getItem(int position) {
            /** Show a Fragment based on the position of the current screen */
            if (position == 0) {
                return fragmentAllPlaylist;
            } else
                return fragmentUserPlaylist;
        }

        @Override
        public int getCount() {
            // Show 2 total pages.
            return 2;
        }
    }
}

最后一个片段显示在viewPager上:

And finally one fragment displayed on the viewPager:

public class SlideToutesPlaylist extends Fragment {


    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(true);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View myView = inflater.inflate(R.layout.playlistall, container, false);
        AffichePlaylist(myView);
        return myView;
    }

    public void AffichePlaylist(View myView){
        ExecHttpGetRequest requete = new ExecHttpGetRequest();
        requete.execute("an IP");
        LinearLayout aaa = (LinearLayout) myView.findViewById(R.id.aaa);

        try {
            if (requete.get() != null) {
                JSONObject jsonObj = new JSONObject(requete.get());
                JSONArray jSon = jsonObj.getJSONArray("valeurs");
                for (int i = 0; i < jSon.length(); i++) {
                    JSONObject c = jSon.getJSONObject(i);
                    final String nom_playlist = c.getString("nom_playlist");
                    final String id_playlist = c.getString("id_playlist");
                    final String id_createur = c.getString("id_createur");
                    final String nb_vote = c.getString("nb_vote");
                    Button bouton = new Button(getContext());
                    bouton.setText(nom_playlist);
                    aaa.addView(bouton);

                }
            }
        } catch (InterruptedException | ExecutionException | JSONException e) {
            e.printStackTrace();
        }


    }
}

编辑好吧,我终于用您的解决方案解决了我的问题,但是现在我遇到了这个问题:

EDIT Ok finally i solved my problem with your solution but now i have this problem :

java.lang.NullPointerException: Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference
                  at android.support.v4.app.FragmentManagerImpl.getFragment(FragmentManager.java:873)
                  at android.support.v4.app.FragmentStatePagerAdapter.restoreState(FragmentStatePagerAdapter.java:215)
                  at android.support.v4.view.ViewPager.onRestoreInstanceState(ViewPager.java:1481)
                  at android.view.View.dispatchRestoreInstanceState(View.java:14762)
                  at android.view.ViewGroup.dispatchRestoreInstanceState(ViewGroup.java:3123)
                  at android.view.ViewGroup.dispatchRestoreInstanceState(ViewGroup.java:3129)
                  at android.view.View.restoreHierarchyState(View.java:14740)
                  at android.support.v4.app.Fragment.restoreViewState(Fragment.java:475)
                  at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1329)
                  at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1528)
                  at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1595)
                  at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:757)
                  at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2355)
                  at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2146)
                  at android.support.v4.app.FragmentManagerImpl.optimizeAndExecuteOps(FragmentManager.java:2098)
                  at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2008)
                  at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:710)
                  at android.os.Handler.handleCallback(Handler.java:746)
                  at android.os.Handler.dispatchMessage(Handler.java:95)
                  at android.os.Looper.loop(Looper.java:148)
                  at android.app.ActivityThread.main(ActivityThread.java:5443)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)

推荐答案

要在另一个片段中填充片段,您需要使用getChildFragmentManager()而不是myContext.getSupportFragmentManager().

To inflate fragments inside another fragment you need tu use getChildFragmentManager() instead ofmyContext.getSupportFragmentManager().

按以下方式使用FragmentStatePagerAdapter:

Use FragmentStatePagerAdapter as follows:

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

import java.util.ArrayList;
import java.util.List;

public class ViewPagerAdapter extends FragmentStatePagerAdapter {

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


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

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

//Check if the list is empty before return the size
@Override
public int getCount() {
    return mFragmentList != null ? mFragmentList.size() : 0;
}


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

public void addFragment(Fragment fragment) {
    mFragmentList.add(fragment);
}

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

}

然后在片段中添加要显示在viewPager中的片段:

Then in your fragment just add the fragments you want to show in the viewPager:

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

...

viewPager = (ViewPager) view.findViewById(R.id.viewpager);
adapter = new ViewPagerAdapter(getChildFragmentManager());
adapter.addFragment(SlideToutesPlaylist.newInstance(), getString(R.string.title));
adapter.addFragment(SlideToutesPlaylist.newInstance(), getString(R.string.title));
viewPager.setAdapter(adapter);
viewPager.setOffscreenPageLimit(2);

这篇关于更改片段后,ViewPager的内容消失的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 00:46