Как отобразить данные в виде сетки из json api - PullRequest
0 голосов
/ 03 июля 2018

Я работаю над проектом, в котором я хочу отображать данные в виде сетки из JSON API. Пожалуйста, помогите мне; Я новичок в этом. Мой JSON состоит из URL-адреса изображения, и я также хочу, чтобы это изображение отображалось в виде сетки. Ниже мой JSON API.

{
    "status": 200,
    "msg": "success",
    "data": [
        {
            "category_name": "ELECTRONICS",
            "category_description": "ELECTRONICS Items",
            "category_image": "images/uploads/a8cee9e723f669813b999ee6bfe611f42018-05-1712-36-17.jpg"
        },
        {
            "category_name": "Sports",
            "category_description": "Sports Accesories",
            "category_image": "images/uploads/76f2c9778df71ae83d04bc0d6178042f2018-05-1712-36-17.jpg"
        },
        {
            "category_name": "Dress",
            "category_description": "All Kind of dress",
            "category_image": "images/uploads/05a5efb96308db381116e90478fce2272018-05-1712-36-17.jpg"
        },
        {
            "category_name": "Cars",
            "category_description": "Automobiles",
            "category_image": ""
        }
    ]
}

Ответы [ 4 ]

0 голосов
/ 05 февраля 2019

все, что вам нужно сделать, это сделать ваши модели и адаптер, а затем использовать GridLayoutManager при заполнении данных в RecyclerView

0 голосов
/ 03 июля 2018

Вот краткое решение вашей проблемы:

  • Создайте класс, который будет создавать объекты со следующими атрибутами: categoryName, CategoryDescription и category_image.
  • Вам нужно уметь анализировать JSON и, когда вы это делаете, создавать объекты указанного выше класса: смотреть
  • Используйте RecyclerView с GridLayoutManager ( это видео-помощь , в нем используется LinearLayoutManager, поэтому вместо него необходимо использовать GridLayoutManager)

GridLayoutManager упорядочивает элементы в двумерной сетке, например, квадраты на шахматной доске. Использование RecyclerView с GridLayoutManager обеспечивает такие же функциональные возможности, как и старый макет GridView.

0 голосов
/ 03 июля 2018

PhotosFragment.java

public class PhotosFragment extends Fragment{

    private Contxt ctx;
    private ViewGroup vg;

    private RecyclerView recyclerPhotos;
    private PhotosGridAdapter photosGridAdapter;

    private ArrayList<PagePhotosModel> allPhotosList = new ArrayList<>();

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        ctx = context;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        vg = (ViewGroup) inflater.inflate(R.layout.fragment_photos, container, false);
        vg.setClickable(true);
        return vg;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        findViews();

        initRecycler();

        getDataFromSever();
    }

    private void findViews() {
        recyclerPhotos = (RecyclerView) getView().findViewById(R.id.recycler_photos);
    }

    private void initRecycler(ArrayList<PagePhotosModel> allPhotosList) {
            photosGridAdapter = new PhotosGridAdapter(ctx, allPhotosList, PhotosFragment.this);
            RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(ctx, 2);
            recyclerPhotos.setLayoutManager(mLayoutManager);
            recyclerPhotos.setItemAnimator(new DefaultItemAnimator());
            recyclerPhotos.setAdapter(photosGridAdapter);
    }

    // Implement retrofit Or volley to get json data from server
    private getDataFromSever(){

    //here use the method whatever you want to get data from serverand add data to allPhotosList

    photosGridAdapter.updateDataInList(allPhotosList);

    }
}

fragment_photos.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorGrayBg"
    android:orientation="vertical">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_photos"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginBottom="@dimen/_4sdp"
        android:layout_marginTop="@dimen/_4sdp"
        android:stretchMode="columnWidth"
        android:visibility="visible">

    </android.support.v7.widget.RecyclerView>

</LinearLayout>

PhotosGridAdapter.java

public class PhotosGridAdapter extends RecyclerView.Adapter<PhotosGridAdapter.MyViewHolder> {

    private Context ctx;
    private PhotosFragment photosFragment;
    private ArrayList<PagePhotosModel> photosList;

    public class MyViewHolder extends RecyclerView.ViewHolder {
        private final ImageView imgPhoto;

        public MyViewHolder(View view) {
            super(view);
            imgPhoto = (ImageView) view.findViewById(R.id.img_photo);
        }
    }

    public PhotosGridAdapter(Context ctx, ArrayList<PagePhotosModel> photosList, PhotosFragment photosFragment) {
        this.ctx = ctx;
        this.photosList = photosList;
        this.photosFragment = photosFragment;
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_photo_grid, parent, false);

        return new MyViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(final MyViewHolder holder, final int position) {
        final PagePhotosModel photosModel = photosList.get(position);

        Glide.with(ctx)
                .load(UrlImage)
                .asBitmap()
                .centerCrop()
                .placeholder(R.drawable.image_placeholder) // can also be a drawable
                .error(R.drawable.image_placeholder) // will be displayed if the image cannot be loaded
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .override(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
                .into(imgUserImage);

    }

    @Override
    public int getItemCount() {
        return photosList.size();
    }

    public void updateDataInList(ArrayList<PagePhotosModel> photosList) {
        this.photosList = photosList;
        notifyDataSetChanged();
    }

}

item_photo_grid.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

                <ImageView
                    android:id="@+id/img_photo"
                    android:layout_width="match_parent"
                    android:layout_height="@dimen/_130sdp"
                    android:background="@color/colorGrayLight"
                    android:src="@drawable/image_placeholder" />


</FrameLayout>
0 голосов
/ 03 июля 2018

Ваш файл JSON может находиться на сервере или в папке ресурсов, и использование GridLayoutManager recyclerView вместо LinearLayoutManager хорошо для того, что вы собираетесь делать.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...