Using only one Fragment with RecyclerView for multiple TabLayout , not updating data correctly on tabs change

不羁的心 提交于 2019-12-25 03:27:02

问题


There is a question similar to me, but that solution didn't work for my case. The question I have referred is this I have a fragment named "HomeFragment" which consists of a VieWPager and TabLayout. I am adding tabs dynamically from the backend. So I am using another Fragment named "SecondFragment" for all tabs since all tabs contain a RecyclerView only. I am populating the RecyclerView onCreate() of the SecondFragment. My issue comes here that when I swipe or change the tab, the RecyclerView not updating correctly. On continuing swiping, the data changes but it does not correspond to the selected tab. I have logged the flow and I am getting correct data from backend on swiping, but it does not updating the RrecyclerView.

My HomeFragment class is

public class HomeFragment extends Fragment implements HTTPCallback {

private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private OnFragmentInteractionListener mListener;
private RecyclerView recyclerView;
private CardView cardview;
private boolean isShow;
View rootview;
private Toolbar toolbar;
private ImageView imageView, tabBg;
private CollapsingToolbarLayout collapsingToolbar;
private TabLayout mTabLayout;
Context context;
private ViewPager mViewPager, mViewPager1;
AppBarLayout appBarLayout;
Integer url_size;
int i;
boolean stopSliding = false;
String url, url2;
String message, version;
private ArrayList<HomeModel> planList;
JSONObject jsonObject, jsonObject2;
JSONArray jsonArray, jsonArray2;
ViewPagerAdapter adapter;

List<Product> products;
int numTab = 0;
private SharedPreferences sharedPreferences;
private SharedPreferences.Editor editor;

public HomeFragment() {
}

public static HomeFragment newInstance(String param1, String param2) {
    HomeFragment fragment = new HomeFragment();
    Bundle args = new Bundle();
    args.putString(ARG_PARAM1, param1);
    args.putString(ARG_PARAM2, param2);
    fragment.setArguments(args);
    return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {

    }
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    rootview = inflater.inflate(R.layout.fragment_home, container, false);
    appBarLayout = (AppBarLayout) rootview.findViewById(R.id.appbar);
    mViewPager1 = (ViewPager) rootview.findViewById(R.id.view_pager);
    collapsingToolbar = (CollapsingToolbarLayout) rootview.findViewById(R.id.collapsing_toolbar);
    sharedPreferences = getContext().getSharedPreferences("spade", Context.MODE_PRIVATE);
    editor = sharedPreferences.edit();

    mViewPager = (ViewPager) rootview.findViewById(R.id.viewpager);
    mTabLayout = (TabLayout) rootview.findViewById(R.id.tabs);

    mTabLayout.setSelectedTabIndicatorColor(Color.parseColor("#FF0000"));
    mTabLayout.setSelectedTabIndicatorHeight((int) (5 * getResources().getDisplayMetrics().density));
    mTabLayout.setTabTextColors(Color.parseColor("#727272"), Color.parseColor("#FF0000"));

    new HTTPRequest(getContext(), null, null, HTTPRequest.METHOD.GET, this).execute(url2);

    mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
            if (position == 0) {
                appBarLayout.setExpanded(true);

            } else {
                appBarLayout.setExpanded(false);
            }
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    });

    try {

    } catch (Exception e) {
        e.printStackTrace();
    }

    mTabLayout.setOnTabSelectedListener(
            new TabLayout.ViewPagerOnTabSelectedListener(mViewPager) {
                @Override
                public void onTabSelected(TabLayout.Tab tab) {
                    super.onTabSelected(tab);

                    mViewPager.setCurrentItem(tab.getPosition());
                    numTab = tab.getPosition();
                    HomeModel browsePlan = planList.get(numTab);
                    editor.putString("tab", browsePlan.getName()).commit();
                }
            });

    return rootview;
}

public void onButtonPressed(Uri uri) {
    if (mListener != null) {
        mListener.onFragmentInteraction(uri);
    }
}

@Override
public void onConnectionStarted() {
}

@Override
public void onConnectionFailed() {
}

@Override
public void onCompleted(JSONObject resultData) {

    HomeModel model;
    planList = new ArrayList<>();
    adapter = new ViewPagerAdapter(getChildFragmentManager());
    try {
        jsonArray = resultData.getJSONArray("details");
        editor.putString("tab", jsonArray.getJSONObject(0).getString("name"));
        editor.commit();
        for (int i = 0; i < jsonArray.length(); i++) {

            jsonObject2 = jsonArray.getJSONObject(i);
            model = new HomeModel();
            model.setCatid(jsonObject2.getString("id"));
            model.setImage(jsonObject2.getString("image"));
            model.setName(jsonObject2.getString("name"));
            planList.add(model);
            setupViewPager(mViewPager, jsonObject2.getString("name"));

        }
        setAdapter();
    } catch (JSONException e) {
        e.printStackTrace();
    }

}

private void setAdapter() {

    appBarLayout.setExpanded(false);
    mViewPager.setAdapter(adapter);
    mTabLayout.setupWithViewPager(mViewPager);
}

public interface OnFragmentInteractionListener {
    // TODO: Update argument type and name
    void onFragmentInteraction(Uri uri);
}

private void setupViewPager(ViewPager mViewPager, String name) {
    adapter.addFragment(new SecondFragment(), name);
    mViewPager.setOffscreenPageLimit(1);
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

}

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

}

SecondFragment class is

public class SecondFragment extends Fragment implements HTTPCallback {

private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
String mParam1;
String mParam2;
Button solo, grp;
View rootview;
Fragment fragment;
String url;
JSONObject jsonObject, jsonObject2;
JSONArray jsonArray, jsonArray2;
private ArrayList<Spaceship> planList;
RecyclerView rv;
private RecyclerHomeAdapter adapter = new RecyclerHomeAdapter(getContext(), planList);
;
private SharedPreferences sharedPreferences;
String tab_name;

private OnFragmentInteractionListener mListener;

public SecondFragment() {
}

public static SecondFragment newInstance(String s, String s1) {
    SecondFragment fragment = new SecondFragment();
    Bundle args = new Bundle();
    return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
        mParam1 = getArguments().getString(ARG_PARAM1);
        mParam2 = getArguments().getString(ARG_PARAM2);
    }
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    rootview = inflater.inflate(R.layout.fragment_second, container, false);
    sharedPreferences = getContext().getSharedPreferences("spade", Context.MODE_PRIVATE);

    tab_name = sharedPreferences.getString("tab", "onnumilla");
    rv = (RecyclerView) rootview.findViewById(R.id.rv);
    rv.setLayoutManager(new LinearLayoutManager(getContext()));
    url = "My_url_here";

    HashMap<String, String> data = new HashMap<String, String>();

    data.put("name", tab_name);

    new HTTPRequest2(getContext(), data, null, HTTPRequest2.METHOD.POST, this).execute(url);


    return rootview;
}

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if (isVisibleToUser) {

        adapter.notifyDataSetChanged();

// getFragmentManager().beginTransaction().detach(this).attach(this).commit(); } }

public void onButtonPressed(Uri uri) {
    if (mListener != null) {
        mListener.onFragmentInteraction(uri);
    }
}

@Override
public void onConnectionStarted() {
}

@Override
public void onConnectionFailed() {
}

@Override
public void onCompleted(JSONObject resultData) {

    Spaceship model;
    planList = new ArrayList<>();
    planList.clear();
    try {
        jsonArray = resultData.getJSONArray("products");
        for (int i = 0; i < jsonArray.length(); i++) {

            jsonObject2 = jsonArray.getJSONObject(i);
            model = new Spaceship();
            model.setName(jsonObject2.getString("package_name"));
            model.setImage(jsonObject2.getString("images"));
            planList.add(model);
        }

        setAdapter();
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

private void setAdapter() {
    adapter = new RecyclerHomeAdapter(getContext(), planList);
    adapter.notifyDataSetChanged();
    rv.setAdapter(adapter);
    adapter.notifyDataSetChanged();
}

public interface OnFragmentInteractionListener {
    // TODO: Update argument type and name
    void onFragmentInteraction(Uri uri);
}

}

This doesn't work for me. But in the setUserVisibleHint(boolean isVisibleToUser) method when i add getFragmentManager().beginTransaction().detach(this).attach(this).commit(); instead of adapter.notifyDataSetChanged(); it works but it takes some time to hide previous data on swiping tab.

Anyone, please suggest me a solution. I have referred many questions but nothing works for me. All your response is appreciated.


回答1:


This seems to be ViewPager page cashing issue. pls call below code from onCreateView() of HomeFragment.

mViewPager.setOffscreenPageLimit(1);


来源:https://stackoverflow.com/questions/52816494/using-only-one-fragment-with-recyclerview-for-multiple-tablayout-not-updating

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!