Как получить разные типы данных в одном фрагменте, используя recyclerview для их отображения - PullRequest
0 голосов
/ 31 марта 2020

У меня есть фрагмент. Во фрагменте несколько (различных) наборов данных должны быть получены с сервера (через другой запрос к базе данных).

Мне удалось получить данные из первого представления в макете, а также использовать RecyclerView на это, но я не могу обернуть голову, как сделать то же самое для других представлений. (Имея совершенно разные типы данных из первого).

См. изображение ниже -

image

Как видите, я получил первый набор данных (этих изображений) из базы данных, используя залп.

explore_fragment. xml

Здесь, я прикрепил recyclerView для каждого набора данных. Только один из них был использован, потому что я не был уверен, что лучшим вариантом будет наличие нескольких recyclerView для одного макета. У того, что используется, есть идентификатор - «theRecyclerView» (Единственное представление recycler, созданное или вызванное java)

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context="fragments.ExploreFragment"
>

<RelativeLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/searchInputSection"
    android:clickable="true"
    android:layout_marginTop="3dp"
    android:layout_marginBottom="20dp"
    >

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/baseline_search_black_48dp"
        android:paddingStart="20dp"
        android:paddingEnd="10dp"
        android:paddingTop="10dp"
        android:paddingBottom="10dp"
        android:id="@+id/searchIcon"
        />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="11dp"
        android:id="@+id/textSearch"
        android:textSize="16sp"
        android:layout_toRightOf="@+id/searchIcon"
        android:text="Search..."
        />

</RelativeLayout>

<View
    android:layout_width="match_parent"
    android:layout_height="2dp"
    android:background="?android:attr/listDivider"
    android:layout_alignBottom="@id/searchInputSection"
    android:id="@+id/divider1"
    />



<RelativeLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/sectionDate"
    android:layout_below="@+id/divider1"
    android:layout_marginTop="5dp"
    >

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/dateSection1"
        android:src="@drawable/calender_2_48dp"
        android:background="@drawable/image_border2"
        android:layout_marginLeft="10dp"
        android:paddingBottom="10dp"
        android:paddingTop="10dp"
        android:scaleType="centerCrop"
        android:layout_marginTop="5dp"
        />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/dateText"
        android:text="2020"
        android:layout_marginLeft="13dp"
        android:layout_toEndOf="@+id/dateSection1"
        android:layout_centerVertical="true"
        />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/seeMoreText1"
        android:text="See more"
        android:layout_alignParentEnd="true"
        android:padding="20dp"
        android:textColor="@color/blue"
        />


</RelativeLayout>

<androidx.recyclerview.widget.RecyclerView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:scrollbars="vertical"
    android:orientation="horizontal"
    android:layout_below="@+id/sectionDate"
    android:id="@+id/theRecyclerView"
    app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
    android:paddingBottom="10dp"
    />


<View
    android:layout_width="match_parent"
    android:layout_height="2dp"
    android:background="?android:attr/listDivider"
    android:layout_alignBottom="@id/theRecyclerView"
    android:id="@+id/divider2"
    />

<RelativeLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/sectionDate2"
    android:layout_below="@+id/divider2"
    android:layout_marginTop="10dp"
    >

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/dateSection2"
        android:src="@drawable/calender_2_48dp"
        android:background="@drawable/image_border2"
        android:layout_marginLeft="10dp"
        android:paddingBottom="10dp"
        android:paddingTop="10dp"
        android:scaleType="centerCrop"
        android:layout_marginTop="5dp"
        />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/dateText2"
        android:text="1992"
        android:layout_marginLeft="13dp"
        android:layout_toEndOf="@+id/dateSection2"
        android:layout_centerVertical="true"
        />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/seeMoreText2"
        android:text="See more"
        android:layout_alignParentEnd="true"
        android:padding="20dp"
        android:textColor="@color/blue"
        />


</RelativeLayout>

<androidx.recyclerview.widget.RecyclerView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:scrollbars="vertical"
    android:orientation="horizontal"
    android:layout_below="@+id/sectionDate2"
    android:id="@+id/theRecyclerView2"
    app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
    android:paddingBottom="10dp"
    />


<View
    android:layout_width="match_parent"
    android:layout_height="2dp"
    android:background="?android:attr/listDivider"
    android:layout_alignBottom="@id/theRecyclerView2"
    android:id="@+id/divider3"
    />

<RelativeLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/sectionDate3"
    android:layout_below="@+id/divider3"
    android:layout_marginTop="10dp"
    >

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/dateSection3"
        android:src="@drawable/outline_whatshot_black_48dp"
        android:background="@drawable/image_border2"
        android:layout_marginLeft="10dp"
        android:paddingBottom="10dp"
        android:paddingTop="10dp"
        android:scaleType="centerCrop"
        android:layout_marginTop="5dp"
        />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/dateText3"
        android:text="Challenges"
        android:layout_marginLeft="13dp"
        android:layout_toEndOf="@+id/dateSection3"
        android:layout_centerVertical="true"
        />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/seeMoreText3"
        android:text="See more"
        android:layout_alignParentEnd="true"
        android:padding="20dp"
        android:textColor="@color/blue"
        />


</RelativeLayout>

<androidx.recyclerview.widget.RecyclerView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:scrollbars="vertical"
    android:orientation="horizontal"
    android:layout_below="@+id/sectionDate3"
    android:id="@+id/theRecyclerView3"
    app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
    android:paddingBottom="10dp"
    />

<View
    android:layout_width="match_parent"
    android:layout_height="2dp"
    android:background="?android:attr/listDivider"
    android:layout_alignBottom="@id/theRecyclerView3"
    android:id="@+id/divider4"
    />

<RelativeLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/sectionDate4"
    android:layout_below="@+id/divider4"
    android:layout_marginTop="10dp"
    >

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/dateSection4"
        android:src="@drawable/outline_trending_up_black_48dp"
        android:background="@drawable/image_border2"
        android:layout_marginLeft="10dp"
        android:paddingBottom="10dp"
        android:paddingTop="10dp"
        android:scaleType="centerCrop"
        android:layout_marginTop="5dp"
        />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/dateText4"
        android:text="Trending #tags"
        android:layout_marginLeft="13dp"
        android:layout_toEndOf="@+id/dateSection4"
        android:layout_centerVertical="true"
        />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/seeMoreText4"
        android:text="See more"
        android:layout_alignParentEnd="true"
        android:padding="20dp"
        android:textColor="@color/blue"
        />


</RelativeLayout>

<androidx.recyclerview.widget.RecyclerView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:scrollbars="vertical"
    android:orientation="horizontal"
    android:layout_below="@+id/sectionDate4"
    android:id="@+id/theRecyclerView4"
    app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
    />

</RelativeLayout>

</ScrollView>

explore_content. xml

Это xml для заполнения содержимого во фрагменте xml. Он имеет только один вид, который является ImageView для первого набора данных, как показано на рисунке выше.

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content">

<RelativeLayout
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:id="@+id/exploreSections"
    >

    <ImageView
        android:layout_width="150dp"
        android:layout_height="150dp"
        android:id="@+id/imagesExplore"
        android:layout_marginRight="5dp"
        android:layout_marginLeft="5dp"
        android:layout_marginTop="10dp"
        android:layout_below="@+id/dateSection1"
        />

</RelativeLayout>
</ScrollView>

ExploreImagesAdapter. java

Это адаптер, который надувает макет explore_content и показывает его содержимое.

public class ExploreImagesAdapter extends 
RecyclerView.Adapter<ExploreImagesAdapter.MyViewHolder> {
private Context context;
private List<ExploreImages> exploreImagesList;
RequestOptions options;
public ExploreImagesAdapter(Context context, List<ExploreImages> exploreImagesList) {
    this.context = context;
    this.exploreImagesList = exploreImagesList;
    options = new
RequestOptions().centerCrop().placeholder(R.drawable.add_photo).error(R.drawable.back_left_icon);
}
@NonNull
@Override
public ExploreImagesAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int 
viewType) {
    View itemView = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.explore_content, parent, false);
    return new ExploreImagesAdapter.MyViewHolder(itemView);
}

@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, int position) { 
Glide.with(context).load(exploreImagesList.get(position).getImage_url()).apply(options).into(holder.imageView);

    /*holder.dateYear.setText(exploreImagesList.get(position).getPhoto_year());*/
}

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

public static class MyViewHolder extends RecyclerView.ViewHolder{

    ImageView imageView;
    TextView dateYear;

    public MyViewHolder(@NonNull View itemView) {
        super(itemView);
        imageView = itemView.findViewById(R.id.imagesExplore);
        /*dateYear = itemView.findViewById(R.id.dateYear);*/


    }
}
}

ExploreImages

Модель для получения данных и настройки данных

public class ExploreImages {

private String image_id;
private String image_url;
private String photo_year;

public ExploreImages(){

}

public ExploreImages(String image_id, String image_url, String photo_year) {
    this.image_id = image_id;
    this.image_url = image_url;
    this.photo_year = photo_year;
}

public String getImage_id() {
    return image_id;
}

public String getImage_url() {
    return image_url;
}

public String getPhoto_year(){
    return  photo_year;
}


public void setImage_id(String image_id) {
    this.image_id = image_id;
}

public void setImage_url(String image_url) {
    this.image_url = image_url;
}

public void setPhoto_year(String photo_year){ this.photo_year = photo_year;}

}

ExploreFragment. java

Фрагмент основного java файла, в котором я устанавливаю адаптер в представление рециркулятора и выполняю сетевые вызовы с помощью Volley.

public class ExploreFragment extends Fragment {

private JsonArrayRequest request;
private RequestQueue requestQueue;
private List<ExploreImages> lstAnime;
private ArrayList<ExploreImages> tempList;
private ExploreImagesAdapter myAdapter;
private RecyclerView recyclerView;

public ExploreFragment() {
    // Required empty public constructor
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

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

    lstAnime = new ArrayList<>();

    View root = inflater.inflate(R.layout.fragment_explore, container, false);

    RelativeLayout searchLayout = root.findViewById(R.id.searchInputSection);

    recyclerView =  root.findViewById(R.id.theRecyclerView);

    recyclerView.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));

    myAdapter = new ExploreImagesAdapter(getContext(), lstAnime);

    recyclerView.setAdapter(myAdapter);

    searchLayout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(getContext(), SearchActivity.class);
            startActivity(intent);
        }
    });


    /* myAdapter.notifyDataSetChanged();*/

    jsonrequest();

    // Inflate the layout for this fragment
    return root;
}

private void jsonrequest() {
    request = new JsonArrayRequest(EndPoints.EXPLORE_IMAGES_URL, new Response.Listener<JSONArray>() {
        @Override
        public void onResponse(JSONArray response) {
            JSONObject jsonObject = null;
            int i;

            for(i=0; i<response.length(); i++){
                try {
                    jsonObject = response.getJSONObject(i);
                    ExploreImages anime = new ExploreImages();
                    anime.setImage_id(jsonObject.getString("id"));
                    anime.setImage_url(jsonObject.getString("url"));
                    anime.setPhoto_year(jsonObject.getString("photo_year"));;
                    Log.e("CHAAAA", "["+response+"]");
                    lstAnime.add(anime);
                }
                catch (JSONException e){
                    e.printStackTrace();
                    Log.e("TESTERROR", "["+response+"]");
                }


            }

            myAdapter.notifyDataSetChanged();

        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

        }
    });

    requestQueue = Volley.newRequestQueue(getContext());
    requestQueue.add(request);
}

private void setRecyclerView(List<ExploreImages> lstAnime) {
    ExploreImagesAdapter myAdapter = new ExploreImagesAdapter(getContext(), lstAnime);
    recyclerView.setAdapter(myAdapter);
    recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
}

}

get_explore_images. php

Файл php, который получает изображения из базы данных. Это для первого набора данных, мне нужно будет сделать разные запросы для других наборов данных, так как они получены из разных таблиц базы данных.

<?php
require_once 'connect.php';
include('functions.php');
$sql = "SELECT * FROM images ORDER BY rand() LIMIT 5";
$result = mysqli_query($conn,$sql);
$response = array();

while($row = mysqli_fetch_array($result)){ 
    $temp['id']=$row['id'];
    $temp['url']=$row['url'];
    $temp['photo_year']=$row['photo_year'];

    array_push($response, $temp);
}

echo json_encode($response);
?>

Я надеюсь, что я попытался прояснить, насколько это возможно Я хочу достичь.

...