Как разобрать JSON на Tablayout - PullRequest
0 голосов
/ 31 октября 2018

Хорошо, у меня есть Json, я хочу проанализировать его на вкладках (если у меня 6 строк, значит, 6 вкладок), я получаю данные, но не могу их проанализировать .. кто-нибудь может помочь ???

public class WallpaperPageActivity extends BaseActivity {


private ViewPager mViewPager;
private TabLayout mTabLayout;
private WallpaperActivityFragmentAdapter wallpaperActivityFragmentAdapter;
private CategoryList resultCategories;
private ArrayList<Category> categoriesTab = new ArrayList<>();
protected ApiInterface service;



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_wallpaper);

    service = RestApiClient.getClient();


    mViewPager = (ViewPager) findViewById(R.id.activity_wallpapers_content_viewpager);
    mTabLayout = (TabLayout) findViewById(R.id.activity_wallpapers_content_tablayout);
    getCategoryNames();

    mViewPager.setAdapter(new WallpaperActivityFragmentAdapter(getSupportFragmentManager(), this, categoriesTab));
    mViewPager.getAdapter().notifyDataSetChanged();

    setTablayoutItemsMode(mTabLayout, categoriesTab);


    mTabLayout.setupWithViewPager(mViewPager);

    setupTabLayout(mTabLayout, categoriesTab);

}


public void getCategoryNames() {
    Call<CategoryList> call = service.requestCategoryList("get_categories_wallpaper");

    call.enqueue(new Callback<CategoryList>() {
        @Override
        public void onResponse(Response<CategoryList> response) {
            Log.d("wow", "Status Code = " + response.code());
            if (response.isSuccess()) {
                // request successful (status code 200, 201)
                resultCategories = response.body();

                for (int i = 0; i < resultCategories.getCategories().size(); i++) {
                    categoriesTab.add(resultCategories.getCategories().get(i));

                }

            } else {
                Log.d("wow", "error = ");
            }

        }

        @Override
        public void onFailure(Throwable t) {
        }
    });
}

public void setTablayoutItemsMode(TabLayout tabLayout, List<Category> categories) {
    if (categories.size() > 3)
        tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
    else {
        tabLayout.setTabMode(TabLayout.MODE_FIXED);
        tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
    }

}
   }

это адаптер фрагмента.

public class WallpaperActivityFragmentAdapter extends FragmentPagerAdapter {




private int PAGE_COUNT = 1;
private ArrayList<Category> categoriesTab;
private Context context;
private Bundle bundle;
private WallpaperActivityFragment fragment;


public WallpaperActivityFragmentAdapter(FragmentManager fm, Context context, ArrayList<Category>  categoriesTab) {
    super(fm);
    this.context = context;
    this.categoriesTab = categoriesTab;
    PAGE_COUNT = categoriesTab.size();
}

@Override
public int getCount() {
    return PAGE_COUNT;
}

@Override
public Fragment getItem(int position) {
    fragment = new WallpaperActivityFragment();
    bundle = new Bundle();
    bundle.putInt("position", position);
    fragment.setArguments(bundle);
    return fragment;
}


@Override
public CharSequence getPageTitle(int position) {
    return categoriesTab.get(position).getCategoryName();
}

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

а это фрагмент

 public class WallpaperActivityFragment extends Fragment {



@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    return inflater.inflate(R.layout.wallpaper_content_fragment,container,false);
}
}

и это xml, который содержит viewpager и tablayout

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">



<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/tablayout_linear"
    android:orientation="horizontal" >

    <include layout="@layout/category_btn"/>


    <android.support.design.widget.TabLayout
        android:id="@+id/activity_wallpapers_content_tablayout"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:background="#FFFFFF"
        app:tabGravity="fill"
        app:tabMaxWidth="0dp"
        app:tabMode="fixed" />



</LinearLayout>


<android.support.v4.view.ViewPager
    android:id="@+id/activity_wallpapers_content_viewpager"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:layout_behavior="@string/appbar_scrolling_view_behavior" />


<View
    android:layout_width="match_parent"
    android:layout_height="2dp"
    android:layout_below="@+id/tablayout_linear"
    android:background="#FFF123" />

Я уже включил его в файл activity_wallpaper ............ Теперь я не могу получить данные с помощью модернизации, но как это сделать (setTabText что-то вроде этого)

конечно, это в BaseActivity

 public void setupTabLayout(TabLayout tabLayout, ArrayList<Category> categoriesTab) {
    for (int i = 0; i < tabLayout.getTabCount(); i++) {
        RelativeLayout customTab = (RelativeLayout) LayoutInflater.from(this).inflate(R.layout.page_content_custom_tab, null);
        TextView tabTitle = (TextView) customTab.findViewById(R.id.activity_music_page_content_tab_title);
        tabTitle.setTextSize(15);
        tabTitle.setText(categoriesTab.get(i).getCategoryName());
        tabTitle.setTextColor(ContextCompat.getColor(this, 0));

        tabLayout.getTabAt(i).setCustomView(customTab);


    }
}

json, который я получаю, содержит идентификатор и название вкладки

{


"categories": [
    {
      "ID": "18",
      "CategoryName": "Inside Yerevan"
    },
    {
      "ID": "1",
      "CategoryName": "Armenia"
    },
    {
      "ID": "2",
      "CategoryName": "National Days"
    },
    {
      "ID": "17",
      "CategoryName": "Armenian Taraz"
    },
    {
      "ID": "3",
      "CategoryName": "Nature"
    },
    {
      "ID": "4",
      "CategoryName": "Animals"
    },
    {
      "ID": "5",
      "CategoryName": "Art"
    },
    {
      "ID": "6",
      "CategoryName": "Travel"
    },
    {
      "ID": "7",
      "CategoryName": "Music"
    },
    {
      "ID": "8",
      "CategoryName": "Flowers"
    },
    {
      "ID": "9",
      "CategoryName": "Food"
    },
    {
      "ID": "10",
      "CategoryName": "Architecture"
    },
    {
      "ID": "11",
      "CategoryName": "Retro"
    },
    {
      "ID": "13",
      "CategoryName": "Architecture"
    },
    {
      "ID": "14",
      "CategoryName": "Funny"
    },
    {
      "ID": "15",
      "CategoryName": "National Holida"
    },
    {
      "ID": "16",
      "CategoryName": "Sky"
    }
  ]
}

Ответы [ 2 ]

0 голосов
/ 01 ноября 2018

Я только что написал свой viewpager и tablayout код внутри ответа сервера, и все работает

public class WallpaperPageActivity extends BaseActivity {


private ViewPager mViewPager;
private TabLayout mTabLayout;
private WallpaperActivityFragmentAdapter wallpaperActivityFragmentAdapter;
private CategoryList resultCategories;
private ArrayList<Category> categoriesTab = new ArrayList<>();
protected ApiInterface service;



 @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wallpaper);

service = RestApiClient.getClient();


mViewPager = (ViewPager) findViewById(R.id.activity_wallpapers_content_viewpager);
mTabLayout = (TabLayout) findViewById(R.id.activity_wallpapers_content_tablayout);
getCategoryNames();



}


public void getCategoryNames() {
Call<CategoryList> call = service.requestCategoryList("get_categories_wallpaper");

call.enqueue(new Callback<CategoryList>() {
    @Override
    public void onResponse(Response<CategoryList> response) {
        Log.d("wow", "Status Code = " + response.code());
        if (response.isSuccess()) {
            // request successful (status code 200, 201)
            resultCategories = response.body();

            for (int i = 0; i < resultCategories.getCategories().size(); i++) {
                categoriesTab.add(resultCategories.getCategories().get(i));
mViewPager.setAdapter(new WallpaperActivityFragmentAdapter(getSupportFragmentManager(),WallpaperPageActivity.this, categoriesTab));
mViewPager.getAdapter().notifyDataSetChanged();

setTablayoutItemsMode(mTabLayout, categoriesTab);


mTabLayout.setupWithViewPager(mViewPager);

setupTabLayout(mTabLayout, categoriesTab);

            }

        } else {
            Log.d("wow", "error = ");
        }

    }

    @Override
    public void onFailure(Throwable t) {
    }
});
  }

public void setTablayoutItemsMode(TabLayout tabLayout, List<Category> categories) {
if (categories.size() > 3)
    tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
else {
    tabLayout.setTabMode(TabLayout.MODE_FIXED);
    tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
}

 }
   }
0 голосов
/ 31 октября 2018

Вы делаете асинхронный вызов, поэтому приложение не знает, когда вы достигли данных. Пожалуйста, добавьте mViewPager.getAdapter().notifyDataSetChanged(); в onResponse обратный вызов после вашего for loop

...