对多个 TabLayout 仅使用一个带有 RecyclerView 的 Fragment,无法在选项卡更改时正确更新数据
Posted
技术标签:
【中文标题】对多个 TabLayout 仅使用一个带有 RecyclerView 的 Fragment,无法在选项卡更改时正确更新数据【英文标题】:Using only one Fragment with RecyclerView for multiple TabLayout , not updating data correctly on tabs change 【发布时间】:2019-03-19 20:48:47 【问题描述】:有一个与我类似的问题,但该解决方案不适用于我的情况。 我提到的问题是 this 我有一个名为“HomeFragment”的片段,它由一个 VieWPager 和 TabLayout 组成。我正在从后端动态添加选项卡。所以我为所有选项卡使用另一个名为“SecondFragment”的片段,因为所有选项卡都只包含一个 RecyclerView。我正在填充 SecondFragment 的 RecyclerView onCreate()。我的问题出现在这里,当我滑动或更改选项卡时,RecyclerView 没有正确更新。继续滑动时,数据会发生变化,但与所选选项卡不对应。我已经记录了流程,并且在刷卡时从后端获取了正确的数据,但它没有更新 RrecyclerView。
我的 HomeFragment 类是
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 类是
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);
这对我不起作用。但是在我添加 getFragmentManager().beginTransaction().detach(this).attach(this).commit();
时的 setUserVisibleHint(boolean isVisibleToUser) 方法中
而不是adapter.notifyDataSetChanged();
它可以工作,但是在滑动选项卡上隐藏以前的数据需要一些时间。
任何人,请给我一个解决方案。我提出了很多问题,但对我没有任何作用。感谢您的所有回复。
【问题讨论】:
请同时发布您的活动代码。 @Manish 我在片段 HomeFragment 中使用标签。这是问题中的第一个代码。与活动无关。在 HomeFragment 中有 TabLayout 和 ViewPager 和 SecondFragment 添加到该 ViewPager 你找到解决办法了吗?? @Hamza 还没有,抱歉回复晚了 【参考方案1】:这似乎是 ViewPager 页面兑现问题。请从 onCreateView() 调用以下代码 的 HomeFragment。
mViewPager.setOffscreenPageLimit(1);
【讨论】:
我必须在问题中描述的 SetUserVisibleHint 方法中添加“getFragmentManager().beginTransaction().detach(this).attach(this).commit();。没有这条线它不起作用即使在设置 mViewPager.setOffscreenPageLimit(1);以上是关于对多个 TabLayout 仅使用一个带有 RecyclerView 的 Fragment,无法在选项卡更改时正确更新数据的主要内容,如果未能解决你的问题,请参考以下文章
带有 TabLayout 的片段内的 ScrollView 不滚动,为啥?
如何在 CollapsingToolbarLayout 中使用带有 Toolbar 的 TabLayout?
带有片段的 NavigationDrawer 内的 Android TabLayout