如何从Web服务将ViewPager中的片段添加到TabLayout?

时间:2018-08-05 17:52:12

标签: android android-fragments android-viewpager android-tablayout

我正在尝试将标签页动态添加到基于envir = my.eny的应用程序中。TabLayout-ViewPager-Fragment使用自定义视图,并在TabLayout的顶部带有ImageView

我现在要根据从PHP / MySQL Web服务创建的TextViewJSONObjects的数量添加标签。我在JSONArray中尝试了以下方法,但是抛出了:

PagerAdapter

方法与下面的我的适配器中

java.lang.IllegalStateException: Can't change tag of fragment TstFrag{df80bc8 #0 id=0x7f080157 android:switcher:2131231063:0}: was android:switcher:2131231063:0 now android:switcher:2131231063:1

在我的活动中调用该方法的位置添加片段:

public class FrgAdapter extends FragmentStatePagerAdapter {
private List<Fragment> mFragmentList = new ArrayList<>();
private List<String> mFragmentTitleList = new ArrayList<>();

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

public FrgAdapter(FragmentManager fm, List<Fragment> mFragmentList, List<String> mFragmentTitleList) {
    super(fm);
    this.mFragmentList = mFragmentList;
    this.mFragmentTitleList = mFragmentTitleList;

}

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

public void insertFromJSONObject(JSONObject jsonObject, Fragment fragment, CircularImageView imageView, TextView textView) throws JSONException {
    JSONArray dataArray = jsonObject.getJSONArray("data");

    for (int i = 0; i < dataArray.length(); i++) {
        JSONObject sectionObj = (JSONObject) dataArray.get(i);

        JSONArray sectionsArray = sectionObj.getJSONArray("section");

        for (int j = 0; j < sectionsArray.length(); j++) {
            JSONObject obj = (JSONObject) sectionsArray.get(j);
            Picasso.get().load(obj.getString("imag")).into(imageView);
            mFragmentList.add(fragment);
            mFragmentTitleList.add(obj.getString("name"));
            textView.setText(obj.getString("name"));
            notifyDataSetChanged();
        }
    }
}

@Override
public CharSequence getPageTitle(int position) {
    return null;
}}

这是我的private void setUpViewPager(ViewPager viewPager, View view) { adapter = new FrgAdapter(getSupportFragmentManager()); /*adapter.addFragment(new MleFrag(), "Men"); adapter.addFragment(new FmlFrag(), "Women"); adapter.addFragment(new ChdFrag(), "Children"); adapter.addFragment(new AceFrag(), "Accessories"); */ String url = "https://44091ee6.ngrok.io/Glam/men.json"; AndroidNetworking.get(url) .setPriority(Priority.MEDIUM) .build() .getAsJSONObject(new JSONObjectRequestListener() { @Override public void onResponse(JSONObject response) { try { adapter.insertFromJSONObject(response, new TstFrag(), view.findViewById(R.id.circularImageView), view.findViewById(R.id.text_header)); adapter.notifyDataSetChanged(); } catch (JSONException e) { e.printStackTrace(); } } @Override public void onError(ANError anError) { Toast.makeText(getApplicationContext(), anError.toString(), Toast.LENGTH_LONG).show(); } }); adapter.notifyDataSetChanged(); viewPager.setAdapter(adapter); } 。在我的脑海中,我想在需要的每个时间重复使用这个Fragment

Fragment

2 个答案:

答案 0 :(得分:1)

您可以尝试以下方法:

adapter.insertFromJSONObject(response, view.findViewById(R.id.circularImageView), view.findViewById(R.id.text_header));
adapter.notifyDataSetChanged();

public void insertFromJSONObject(JSONObject jsonObject, CircularImageView imageView, TextView textView) throws JSONException {
    JSONArray dataArray = jsonObject.getJSONArray("data");

    for (int i = 0; i < dataArray.length(); i++) {
        JSONObject sectionObj = (JSONObject) dataArray.get(i);

        JSONArray sectionsArray = sectionObj.getJSONArray("section");

        for (int j = 0; j < sectionsArray.length(); j++) {
            JSONObject obj = (JSONObject) sectionsArray.get(j);

            Picasso.get().load(obj.getString("imag")).into(imageView);
            mFragmentList.add(new TstFrag());
            textView.setText(obj.getString("name"));
            //mFragmentTitleList.add(obj.getString("name"));
            notifyDataSetChanged();
        }
    }
}

这里的基本思想是为TstFrag的每个条目创建FrgAdapter的新实例。

答案 1 :(得分:1)

考虑手动将片段添加到viewPager,但只需在viewPager适配器上实现getItem和&instantiateItem方法即可。然后viewPager将控制新instantiation的{​​{1}}或已重用选中此answer for complete adapter

TstFrag

更新

@Override
public Fragment getItem(final int pos) {
    return TstFrag.getInstance(dataList.get(pos));
}


@NonNull
@Override
public Object instantiateItem(ViewGroup container, int position) {
    Fragment fragment = (Fragment) super.instantiateItem(container, position);
    registeredFragments.put(position, fragment);
    return fragment;
}

@Override
public void destroyItem(ViewGroup container, int position, Object object) {
    registeredFragments.remove(position);
    super.destroyItem(container, position, object);
}

替换

  

public class DataModel implements Serializable{ private String name; private String image; // GETTER && SETTER }

使用

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

insertFromJSONObject

 private List<DataModel> dataList = new ArrayList<>();

TstFrag

    dataList.clear();
    for (int j = 0; j < sectionsArray.length(); j++) {
        JSONObject obj = (JSONObject) sectionsArray.get(j);
        final DataModel model = new DataModel();
        model.setName(obj.getString("name"));
        model.setImage(obj.getString("imag"));
        // Picasso.get().load(obj.getString("imag")).into(imageView);
        // No need to load image here just fetch for cache if you want.
        Picasso.get().load(model.getImage()).fetch();
        // mFragmentList.add(fragment); // no need handle adding fragment here as mentioned above.
        dataList.add(dataModel);
        // textView.setText(obj.getString("name")); // It's not good to update UI here but update there with fragment on create called mention below.
        // notifyDataSetChanged(); DON'T call this inside the loop but after finish your stuff.
    }
    // Just notify here...
    notifyDataSetChanged();