如何在Android的Recyclerview中添加类似按钮

问题描述 投票:0回答:1

我是一个新的应用程序开发人员android应用程序,需要一些帮助。我需要知道如何在链接到数据库(Mysql)的内部(Recyclerview)中添加“喜欢”按钮,并通过Volley库进行连接以保存所有用户喜欢,并查看每个主题有多少喜欢。图片中的一个例子。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);



    ?>

java android mysql android-recyclerview android-volley
1个回答
0
投票
 @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类中添加类似布尔变量的变量。添加它的getter和setter。在可绘制文件夹中为Like和Not_like添加两个可绘制对象。然后添加此逻辑。希望这会有所帮助。谢谢

© www.soinside.com 2019 - 2024. All rights reserved.