как добавить кнопку лайка в Recyclerview в android - PullRequest
0 голосов
/ 21 февраля 2020

Я разработчик нового приложения android, и мне нужна помощь. Пожалуйста. Мне нужно знать, как добавить кнопку «Мне нравится» внутри (Recyclerview), связанную с базой данных (Mysql), и подключиться через библиотеку Volley, чтобы сохранить все лайки пользователей. И посмотреть, сколько лайков имеет каждый топи c. Пример на рисунке .. enter image description here

Мне нужно добавить его в этот прикрепленный проект.

MainActivity

public class MainActivity extends AppCompatActivity {
    List<RecyclerViewData> recyclerViewDataList;
    RecyclerView recyclerView;
    private RVAdapter rvAdapter;
    private static final String TAG="apple";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        setTitle("Employee List");

        recyclerViewDataList=new ArrayList<>();

        recyclerView=findViewById(R.id.recyclerView);

        LinearLayoutManager linearLayoutManager=new LinearLayoutManager(this);
        recyclerView.setLayoutManager(linearLayoutManager);
        MakeVolleyConnection();

    }

    private void MakeVolleyConnection() {
        recyclerViewDataList = new ArrayList<>();
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET,
                "http://10.0.13.45/v/parsing.php", null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {

                    JSONArray dataArray = response.getJSONArray("data");
                    for (int i = 0; i < dataArray.length(); i++) {
                        JSONObject userData = dataArray.getJSONObject(i);
                        RecyclerViewData recyclerViewData = new RecyclerViewData();
                        recyclerViewData.setId(userData.getInt("id"));
                        recyclerViewData.setFirstname(userData.getString("first_name"));
                        recyclerViewData.setLastname(userData.getString("last_name"));
                        recyclerViewData.setAvatar(userData.getString("avatar"));
                        recyclerViewDataList.add(recyclerViewData);

                    }
                    rvAdapter = new RVAdapter(recyclerViewDataList, MainActivity.this);
                    recyclerView.setAdapter(rvAdapter);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

                Toast.makeText(MainActivity.this, ""+error.networkResponse,Toast.LENGTH_SHORT).show();
            }
        });

        MySingleton.getInstance(this).addToRequestQueue(jsonObjectRequest);
    }
}

MySingleton

public class MySingleton {
    private static MySingleton mInstance;
    private RequestQueue mRequestQueue;
    private static Context mContext;

    private MySingleton(Context context){
        // Specify the application context
        mContext = context;
        // Get the request queue
        mRequestQueue = getRequestQueue();
    }

    public static synchronized MySingleton getInstance(Context context){
        // If Instance is null then initialize new Instance
        if(mInstance == null){
            mInstance = new MySingleton(context);
        }
        // Return MySingleton new Instance
        return mInstance;
    }

    public RequestQueue getRequestQueue(){
        // If RequestQueue is null the initialize new RequestQueue
        if(mRequestQueue == null){
            mRequestQueue = Volley.newRequestQueue(mContext.getApplicationContext());
        }

        // Return RequestQueue
        return mRequestQueue;
    }

    public<T> void addToRequestQueue(Request<T> request){
        // Add the specified request to the request queue
        getRequestQueue().add(request);
    }
}

RecyclerViewData


public class RecyclerViewData {
    private int id;
    private String firstname;
    private String lastname;
    private String avatar;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getFirstname() {
        return firstname;
    }

    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }

    public String getLastname() {
        return lastname;
    }

    public void setLastname(String lastname) {
        this.lastname = lastname;
    }

    public String getAvatar() {
        return avatar;
    }

    public void setAvatar(String avatar) {
        this.avatar = avatar;
    }
}

RVAdapter

public class RVAdapter extends RecyclerView.Adapter<RVAdapter.RVHOLDER> {
    List<RecyclerViewData> recyclerViewDataList;
    Context mContext;

    // Constructor with List and Context which we'll pass from RecyclerView Activity after a connection to Volley. And application context for the listener that we'll implement this later.
    public RVAdapter(List<RecyclerViewData> recyclerViewDataList, Context mContext) {
        this.recyclerViewDataList = recyclerViewDataList;
        this.mContext = mContext;
    }

    // Override the method onCreateViewHolder, which will call the custom view holder that needs to be initialized. We specify the layout that each item to be used, so we can achieve this using Layout Inflator to inflate the layout and passing the output to constructor of custom ViewHolder.
    @NonNull
    @Override
    public RVHOLDER onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View itemView = LayoutInflater.from(mContext).inflate(R.layout.adapter_layout, viewGroup, false);
        RVHOLDER rvholder = new RVHOLDER(itemView);
        return rvholder;
    }


    //onBindViewHolder is for specifying the each item of RecyclerView. This is very similar to getView() method on ListView. In our example, this is where you need to set the user's id, name and image.
    @Override
    public void onBindViewHolder(@NonNull RVHOLDER rvholder, int i) {
        rvholder.id.setText("User id is "+recyclerViewDataList.get(i).getId());
        rvholder.first_name.setText(recyclerViewDataList.get(i).getFirstname() + " " + recyclerViewDataList.get(i).getLastname());
        Picasso.get().load(recyclerViewDataList.get(i).getAvatar()).into(rvholder.avatar);
    }

    //We need to return the size for RecyclerView as how long a RecyclerView is, Our data is in list so passing data.size() will return the number as long as we have.
    @Override
    public int getItemCount() {
        return recyclerViewDataList.size();
    }

    //This is CustomView holder that we had discuss it earlier above and inflated it in onCreateView() method. This constructor links with the xml to set the data, which we set into onBindViewHolder().
    class RVHOLDER extends RecyclerView.ViewHolder {
        TextView id;
        private TextView first_name;
        private ImageView avatar;

        public RVHOLDER(@NonNull View itemView) {
            super(itemView);
            id = itemView.findViewById(R.id.id);
            first_name = itemView.findViewById(R.id.firstname_lastname);
            avatar = itemView.findViewById(R.id.avatar);
        }
    }
}

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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="match_parent"
    android:orientation="vertical">

    <androidx.cardview.widget.CardView
        android:id="@+id/card_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        card_view:cardCornerRadius="4dp"
        card_view:cardUseCompatPadding="true">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <ImageView
                android:id="@+id/avatar"
                android:layout_width="50dp"
                android:layout_height="50dp"
                android:layout_marginRight="16dp"
                android:scaleType="fitCenter" />

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical">

                <TextView
                    android:id="@+id/firstname_lastname"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:textAppearance="?android:textAppearanceMedium" />

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

            </LinearLayout>
        </LinearLayout>

    </androidx.cardview.widget.CardView>

</RelativeLayout>

<?php

$con=mysqli_connect("localhost","root","root","test");

$sql="SELECT * FROM testtable";

$result=mysqli_query($con,$sql);

$data=array();
while($row=mysqli_fetch_assoc($result)){
$data["data"][]=$row;
}
        header('Content-Type:Application/json');    
    echo json_encode($data);



    ?>

Ответы [ 2 ]

0 голосов
/ 21 февраля 2020
    @Override
        public void onBindViewHolder(@NonNull RVHOLDER rvholder, int i) {
            rvholder.id.setText("User id is "+recyclerViewDataList.get(i).getId());
            rvholder.first_name.setText(recyclerViewDataList.get(i).getFirstname() + " " + recyclerViewDataList.get(i).getLastname());
            Picasso.get().load(recyclerViewDataList.get(i).getAvatar()).into(rvholder.avatar);


 Picasso.get().load(gContextCompat.getDrawable(getActivity(), if(recyclerViewDataList.get(i).getLiked())R.drawable.liked else R.drawable.not_like).into(rvholder.like);


}
0 голосов
/ 21 февраля 2020
 @Override
    public void onBindViewHolder(@NonNull RVHOLDER rvholder, int i) {
        rvholder.id.setText("User id is "+recyclerViewDataList.get(i).getId());
        rvholder.first_name.setText(recyclerViewDataList.get(i).getFirstname() + " " +
                recyclerViewDataList.get(i).getLastname());
        Picasso.get().load(recyclerViewDataList.get(i).getAvatar()).into(rvholder.avatar);
        if()
    }
    if (recyclerViewDataList.get(i).getLiked()) {
        // liked image
        Picasso.get().load(gContextCompat.getDrawable(getActivity(), R.drawable.liked);).into(rvholder.like);
    } else {
        // without like image
        Picasso.get().load(gContextCompat.getDrawable(getActivity(), R.drawable.not_like);).into(rvholder.like);
    }

Добавить логическую переменную в классе RecyclerViewData. Добавьте геттер и сеттер этого. Добавьте два рисованных объекта в папку для рисования для Like и Not_like. Затем добавьте этот лог c. Надеюсь, это поможет. Спасибо

...