如何在 RecyclerView 中将 OnClickListener 设置为两个按钮? [英] How can I set OnClickListener to two buttons in RecyclerView?

查看:16
本文介绍了如何在 RecyclerView 中将 OnClickListener 设置为两个按钮?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 android 应用程序中,我有一个活动来显示 RecyclerView,其中每一行由一个 TextView 和 2 个按钮组成.就这样:

In my android app I have one activity to show a RecyclerView in which each row is composed by a TextView and 2 buttons. Just like that:

好吧,根据互联网的许多解释,我制作了这个适配器:

Well, following many explanations of internet I have made this Adapter:

public class ListAdapter extends 
RecyclerView.Adapter<ListAdapter.ViewHolder> {

    private LayoutInflater layoutInflater;
    protected Vector<List> lists;

    public ListAdapter(Context context, Vector lists) {
        layoutInflater = (LayoutInflater) 
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        this.lists = lists;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = layoutInflater.inflate(R.layout.listadapter, null);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        List list = lists.elementAt(position);
        holder.name.setText(list.getName());
        //holder.delete.set HOW DO I GET BUTTON HERE?
    }

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

    public static class ViewHolder extends RecyclerView.ViewHolder 
implements View.OnClickListener {
        public TextView name;
        public Button edit;
        public Button delete;

        public ViewHolder(View itemView) {
            super(itemView);
            name = (TextView) itemView.findViewById(R.id.listname);
            edit = (Button) itemView.findViewById(R.id.edit);
            delete = (Button) itemView.findViewById(R.id.delete);

            edit.setOnClickListener(this);
        }

        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.edit:
                    break;
                case R.id.delete:
                    break;
                default:
                    break;
            }
        }
    }
}

我还没有找到在 recyclerview 的每个视图中有 2 个按钮的示例(只有添加图像的示例),如第一张图像.我的意思是,我想我的 RecyclerView 中有 10 个 List 元素,我怎么能在每个元素的一侧都有一个带有 List 名称和 2 个按钮并处理 clickListener 的 TextView?如下图所示,这是我亲手制作的,让您看看我在说什么:

I haven't found examples of having 2 buttons (there are only examples of adding images) in each view of the recyclerview, as in the first image. I mean, guess I have 10 List elements in my RecyclerView, how can I have in each of them to one side a TextView with the name of the List and 2 buttons and handle clickListener?. As in the following image, which I have done by hand for you to see what I am talking about:

这是将显示recyclerView的活动;不要考虑它,因为我很确定方法是错误的.我从 sqlite 数据库获取列表信息:

This is the activity that will show the recyclerView; don't take it into account because I am pretty sure the way is wrong. I get lists information from sqlite database:

public class ShowListOfLists extends AppCompatActivity {

private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_show_list_of_lists);
    LocalDB localDB = new LocalDB(this, "localBD", null, 1);
    Vector <List> ListAdapter = localDB.getAllPrivateList();

    recyclerView = (RecyclerView) findViewById(R.id.recyclerviewlistas);
    recyclerView.setAdapter(new ListAdapter(this, ListAdapter));
    layoutManager = new LinearLayoutManager(this);
    recyclerView.setLayoutManager(layoutManager);
}

列表具有以下属性:

-idList int
-name String
-Description String
-creationDate Date
-active int (0 or 1)
-deactivationDate Date

提前致谢.

/********************************编辑********************************************/

/*******************************EDIT****************************************/

谢谢你,我已经能够展示 recyclerView 并且它运行良好.但我看到了:

Thank to you I have been able to show the recyclerView and it works well. But I see that:

取而代之的是:

这是适配器的 XML 代码和设计:

This the XML code and design of the adapter:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="60dp"
android:background="@drawable/rectangle_bg"
android:orientation="horizontal"
android:weightSum="1"
android:layout_marginTop="5dp">

<TextView
    android:id="@+id/listname"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_marginTop="20dp"
    android:layout_weight="0.75"
    android:gravity="center_vertical"
    android:text="TextView"
    android:textSize="15sp"/>

<LinearLayout
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:layout_weight="0.25"
    android:gravity="end"
    android:orientation="vertical">

    <ImageButton
        android:id="@+id/delete"
        android:layout_width="match_parent"
        android:layout_height="30dp"
        android:background="@android:color/transparent"
        android:contentDescription="Delete"
        app:srcCompat="@android:drawable/ic_menu_delete" />

    <ImageButton
        android:id="@+id/edit"
        android:layout_width="match_parent"
        android:layout_height="30dp"
        android:background="@android:color/transparent"
        android:contentDescription="Edit"
        app:srcCompat="@android:drawable/ic_menu_edit" />

    </LinearLayout>

</LinearLayout>

这是recyclerview的XML

And this is the XML of the recyclerview

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.RecyclerView 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    tools:context="com.pc.kanayel.runoutof.ShowListOfLists"
    android:orientation="vertical"
    android:id="@+id/recyclerviewlistas">

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

推荐答案

您只需要向 ListAdapter 添加一些代码.在那里,您必须实现 onClickListener.您案例的代码应该类似于下面的代码.

You just need to add some code to your ListAdapter. It is there, where you have to implement onClickListener. The code for your case should look something like the one below.

您可以传递任何需要的参数.这取决于您想要实现的功能.这里我演示了传递在列表内单击的项目的顺序.

You can pass any parameter you need to. It depends on the functionality you want to achieve. Here I have demonstrated passing the order of item clicked inside of list.

选项 1(高效节能)

那么,下面的代码实际上是什么意思?您已经创建了一个 ViewHolder 并实现了 OnClickListener.那是正确的.现在您需要将 OnClickListener 设置为两个按钮.但是这些按钮在点击时会做什么是由我们在 ViewHolder 内部创建的 interface 定义的.

So, what does the code below actually mean? You have already created a ViewHolder and implemented OnClickListener. That is correct. Now you need to set OnClickListener to two buttons. But what these buttons will do when clicked is defined by the interface we created inside of ViewHolder.

当应用程序运行时,RecyclerView 将创建尽可能多的 ViewHolder,通过为每个 Viewholder 调用 onCreateViewHolder() 方法来用列表项填充可用屏幕.当您向上/向下滚动时,这些 ViewHolders 将被重用.不调用OnCreateViewHolder(),只调用onBindViewHolder()来更新viewholder的内容.下面的代码使得,当创建 ViewHolder 时,它还会创建一个 MyClickListener ,该 MyClickListener 将由 viewholder 的 OnClickListener 使用,并且当 viewholder 被重用时,它不会创建新的 <代码>OnClickListener.这意味着我们的方法是高效的.

When app will run RecyclerView will create as many ViewHolders as it is needs to fill the available screen with list items by calling onCreateViewHolder() method for each of viewholders. When you scroll up/down these ViewHolders will be reused. OnCreateViewHolder() is not called, only onBindViewHolder() is called to update the content of viewholder. The code below made so that, when ViewHolder is created it will also create an MyClickListener that will be used by OnClickListener of viewholder and when viewholder is reused it will not create new OnClickListener. It means that our method is performance efficient.

选项 2(效率不高)

您也可以在 onBindViewHolder() 内部使用 setOnClickListener().但是,正如我在上面的段落中提到的,每次滚动以更新 viewholder 的内容时都会调用此方法.现在它每次都会创建新的 OnClickListener 对象.而 Option 1 在每个 ViewHolder 上都有 OnClickListener 并重用它们.

You could also setOnClickListener() inside of onBindViewHolder(). However, as I have mentioned in the paragraph above, this method is called every time you scroll to update the content of viewholder. Now it would create new OnClickListener object everytime. While Option 1 has OnClickListener on every ViewHolder and it reuses them.

选项 1 的代码

public class ListAdapter extends RecyclerView.Adapter<ListAdapter.ViewHolder> {

    private LayoutInflater layoutInflater;
    protected Vector<List> lists;

    public ListAdapter(Context context, Vector lists) {
        layoutInflater = (LayoutInflater) 
        context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        this.lists = lists;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = layoutInflater.inflate(R.layout.listadapter, null);
        ViewHolder holder = new ViewHolder(view, new MyClickListener() {
            @Override
            public void onEdit(int p) {
                // Implement your functionality for onEdit here
            }

            @Override
            public void onDelete(int p) {
                // Implement your functionality for onDelete here
            }
        });
        return holder;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        List list = lists.elementAt(position);
        holder.name.setText(list.getName());
    }

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

    public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

        MyClickListener listener;

        TextView name;
        Button edit;
        Button delete;

        public ViewHolder(View itemView, MyClickListener listener) {
            super(itemView);
            name = (TextView) itemView.findViewById(R.id.listname);
            edit = (Button) itemView.findViewById(R.id.edit);
            delete = (Button) itemView.findViewById(R.id.delete);

            this.listener = listener;

            edit.setOnClickListener(this);
            delete.setOnClickListener(this);
        }

        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.edit:
                    listener.onEdit(this.getLayoutPosition());
                    break;
                case R.id.delete:
                    listener.onDelete(this.getLayoutPosition());
                    break;
                default:
                    break;
            }
        }
    }

    public interface MyClickListener {
            void onEdit(int p);
            void onDelete(int p);
    }
}

编辑第二个问题

要使列表项占据所有宽度,请将 recyclerviewwidth 设置为 match_parent.最好让它成为某些布局的子视图.例如如下所示.

To make list items take all the width set the width of your recyclerview to match_parent. It is also better to make it a child view of some layout. For instance as given below.

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.pc.kanayel.runoutof.ShowListOfLists">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerviewlistas"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

<RelativeLayout>

并且在您的适配器中更改此代码:

And change this code inside of your adapter:

View view = layoutInflater.inflate(R.layout.listadapter, null);

为此:

View view = layoutInflater.inflate(R.layout.listadapter, parent, false);

这篇关于如何在 RecyclerView 中将 OnClickListener 设置为两个按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆