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

查看:61
本文介绍了如何在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:

好吧,在对Internet进行了许多解释之后,我制作了此适配器:

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 ************** **************************/

/*******************************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将创建所需数量的ViewHolders,以通过为每个Viewholder调用onCreateViewHolder()方法来用列表项填充可用屏幕.当您向上/向下滚动时,这些ViewHolders将被重复使用.不调用OnCreateViewHolder(),仅调用onBindViewHolder()来更新Viewholder的内容.进行以下代码,以便在创建ViewHolder时还将创建一个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对象.尽管选项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天全站免登陆