繁体   English   中英

如何处理recyclerView上的按钮单击?

[英]How to handle button click on recyclerView?

我有以下代码,如何处理当前卡标题的按钮单击? 我已经尽力了,但是找不到解决方法。

这是我当前的MainActivity:


public class MainActivity extends AppCompatActivity {

    private RecyclerView mRecyclerView;
    private RecyclerView.Adapter mAdapter;
    private RecyclerView.LayoutManager mLayoutManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);

        mRecyclerView = findViewById(R.id.recycler_view);

        List<DataModel> dataModelList = new ArrayList<>();
        for (int i = 1; i <= 20; ++i) {
            dataModelList.add(new DataModel(i));
        }

        // use this setting to improve performance if you know that changes

        // in content do not change the layout size of the RecyclerView
        mRecyclerView.setNestedScrollingEnabled(false);
        mRecyclerView.setHasFixedSize(true);

        // use a linear layout manager

        mLayoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(mLayoutManager);

        // specify an adapter and pass in our data model list

        mAdapter = new MyAdapter(dataModelList, this);
        mRecyclerView.setAdapter(mAdapter);

        /*
        FloatingActionButton fab = findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });*/
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

这是我当前的MyAdapter:


public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {

    private List<DataModel> dataModelList;
    private Context mContext;
    private View.OnClickListener onClickListener;



    public MyAdapter(List<DataModel> modelList, Context context) {
        dataModelList = modelList;
        mContext = context;
        this.onClickListener = onClickListener;
    }

    public MyAdapter() {

    }

    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        // Inflate out card list item

        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.list_item, parent, false);
        // Return a new view holder

        return new MyViewHolder(view);
    }


    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
        // Bind data for the item at position

        holder.bindData(dataModelList.get(position), mContext);
    }


    @Override
    public int getItemCount() {
        // Return the total number of items

        return dataModelList.size();
    }

    // View holder class whose objects represent each list item

    public static class MyViewHolder extends RecyclerView.ViewHolder {
        public ImageView cardImageView;
        public TextView titleTextView;
        public TextView subTitleTextView;

        public MyViewHolder(@NonNull View itemView) {
            super(itemView);
            cardImageView = itemView.findViewById(R.id.imageView);
            titleTextView = itemView.findViewById(R.id.card_title);
            subTitleTextView = itemView.findViewById(R.id.card_subtitle);


        }

        public void bindData(DataModel dataModel, Context context) {

            /*try {
                InputStream is = (InputStream) new URL("https://storage.googleapis.com/spec-host/mio-staging%2Fmio-material%2F1563837804615%2Fassets%2F1Y_wiJ0LkYvEhVYTLhFazPRmQrN7dtsq7%2Fdevelop-web-2x1-small.png").getContent();
                Drawable d = Drawable.createFromStream(is, "src name");
                cardImageView.setImageDrawable(d);
            } catch (Exception e) {
                Log.i("techrcslog", e.toString());
            }*/

            Picasso.get().load("https://storage.googleapis.com/spec-host/mio-staging%2Fmio-material%2F1563837804615%2Fassets%2F1Y_wiJ0LkYvEhVYTLhFazPRmQrN7dtsq7%2Fdevelop-web-2x1-small.png").into(cardImageView);

            //cardImageView.setImageDrawable(dataModel.getImageDrawable());
            titleTextView.setText(dataModel.getTitle());
            subTitleTextView.setText(dataModel.getSubTitle());
        }
    }
}

这是我当前的DataModel:


public class DataModel {
    private int imageDrawable;
    private String title;
    private String subTitle;

    public DataModel(int id) {
        imageDrawable = R.mipmap.ic_launcher;
        title = String.format(Locale.ENGLISH, "Title %d Goes Here", id);
        subTitle = String.format(Locale.ENGLISH, "Sub title %d goes here", id);
    }

    public int getImageDrawable() {
        return imageDrawable;
    }

    public String getTitle() {
        return title;
    }

    public String getSubTitle() {
        return subTitle;
    }
}

这是我当前的list_item.xml:

<?xml version="1.0" encoding="utf-8"?>
<com.google.android.material.card.MaterialCardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    app:cardCornerRadius="3dp"
    app:cardElevation="5dp">
    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp">

        <ImageView
            android:id="@+id/imageView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            android:adjustViewBounds="true"
            app:srcCompat="@mipmap/ic_launcher" />

        <TextView
            android:id="@+id/card_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="16dp"
            android:layout_marginLeft="16dp"
            android:layout_marginTop="16dp"
            android:text="Title goes here"
            style="@style/TextAppearance.MaterialComponents.Headline6"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/imageView" />

        <TextView
            android:id="@+id/card_subtitle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="8dp"
            android:text="Subtitle goes here"
            style="@style/TextAppearance.MaterialComponents.Caption"
            app:layout_constraintStart_toStartOf="@+id/card_title"
            app:layout_constraintTop_toBottomOf="@+id/card_title" />

        <com.google.android.material.button.MaterialButton
            android:id="@+id/action_button_1"
            style="@style/Widget.MaterialComponents.Button.TextButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="16dp"
            android:text="ACTION 1"
            android:textSize="15sp"
            android:textAppearance="@style/TextAppearance.MaterialComponents.Headline6"
            app:layout_constraintStart_toStartOf="@+id/card_subtitle"
            app:layout_constraintTop_toBottomOf="@+id/card_subtitle" />

        <com.google.android.material.button.MaterialButton
            android:id="@+id/action_button_2"
            style="@style/Widget.MaterialComponents.Button.TextButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="32dp"
            android:layout_marginLeft="32dp"
            android:text="ACTION 2"
            android:textSize="15sp"
            android:textAppearance="@style/TextAppearance.MaterialComponents.Headline6"
            app:layout_constraintBottom_toTopOf="@+id/action_button_1"
            app:layout_constraintStart_toEndOf="@+id/action_button_1"
            app:layout_constraintTop_toBottomOf="@+id/action_button_1" />
    </androidx.constraintlayout.widget.ConstraintLayout>
</com.google.android.material.card.MaterialCardView>

任何帮助都将非常非常好...谢谢!

将以下行添加到MyAdapter类

public interface onItemClick{
void onItemClick(Datamodel model);
}

现在将MyAdapter的构造函数更改为

private onItemClick listener;
public MyAdapter(List<DataModel> modelList, Context context,onItemClick listener){
this.listener = listener;
dataModelList = modelList;
        mContext = context;
}

现在在您的mainActivity中

public class MainActivity extends AppCompatActivity implements MyAdapter.onItemClick

和ovveride方法

@Override
void onItemClick(Datamodel model){
}

通过以下代码替换适配器初始化:mAdapter = new MyAdapter(dataModelList,this,this);

现在在ViewHolder类的onBind方法中添加以下行

  titleTextView.setOnClickListener(new OnClickListener {
    @Overriede
    void onClick(View v){
     listener.onItemClick(dataModel);
    }
  });

一种简单的方法,但不建议这样做:

只需在adapter setOnClickListener中设置onBindViewHolder

@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
    // Bind data for the item at position

    holder.bindData(dataModelList.get(position), mContext);
    holder.someView.setOnClickListener(....);

}

更好的方法是使用interfaces (前面的Kotlin):

  1. 创建一个interface ,例如OnMyViewClickListener
interface OnMyViewClickListener{
    fun onMyViewClickListener(position: Int)
}
  1. 修改您的adapterViewHolder ,使它们将创建的interface作为参数。

    OnBindViewHolder

class MyAdapter(private val list: ArrayList<Item>,
                               private val listener: OnMyViewClickListener): RecyclerView.Adapter<RecyclerView.ViewHolder>() {


    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {

        val view = LayoutInflater.from(parent.context)
                        .inflate(R.layout.recycler_item, parent, false)
        return MyViewHolder(view, listener = listener)

    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        holder.bindData(list[position])
    }

}

然后在您的ViewHolder

class MyViewHolder(itemView: View, private val listener: OnMyViewClickListener): RecyclerView.ViewHolder(itemView), View.OnClickListener {


    init {
        itemView.setOnClickListener(this)
    }

    fun bindData(item: Item) {
        // Set data in your views
    }

    override fun onClick(v: View?) {
        listener.onMyViewClickListener(adapterPosition)
    }

}

然后在包含recyclerView activity/fragment实现此interface

class MyActivity : AppCompatActivity(), OnMyViewClickListener{

    mAdapter = MyAdapter(data = data, listener = this)
    override fun onMyViewClickListener(position: Int) {
       //Handle your click event here
    }

}

就是这样。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM