-1

I have the following code, how do I handle the button click with the current card title? I have already tried everything I can, but just can't found a way to handle it.

This is my current 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);
    }
}

This is my current 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());
        }
    }
}

This is my current 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;
    }
}

This is my current 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>

Any help would be very very good... Thanks!

zedlabs
  • 523
  • 7
  • 18
  • good starting point is here : https://stackoverflow.com/questions/48735221/onclick-for-each-button-inside-recyclerview-items/48735330 but regardless there's quite a few answers. Typically find the position of the cell in the adapter then handle the button click. – yams Aug 20 '19 at 18:59

2 Answers2

2

add the following lines to your MyAdapter class

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

now change the constructor of your MyAdapter to

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

now in your mainActivity

public class MainActivity extends AppCompatActivity implements MyAdapter.onItemClick

and ovveride the method

@Override
void onItemClick(Datamodel model){
}

replace the adapter initialization by following line with mAdapter = new MyAdapter(dataModelList, this,this);

now in onBind method in ViewHolder class add the following lines

  titleTextView.setOnClickListener(new OnClickListener {
    @Overriede
    void onClick(View v){
     listener.onItemClick(dataModel);
    }
  });
Furqan Khan
  • 528
  • 4
  • 14
0

An easy way, but not recommended:

Just setOnClickListener in your onBindViewHolder in adapter.

@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(....);

}

The better way, use interfaces (Kotlin ahead):

  1. Create an interface, say OnMyViewClickListener :
interface OnMyViewClickListener{
    fun onMyViewClickListener(position: Int)
}
  1. Modify your adapter and ViewHolder such that they take this created interface as an argument.

    And in 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])
    }

}

Then in your 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)
    }

}

And then implement this interface in your activity/fragment which contains recyclerView.

class MyActivity : AppCompatActivity(), OnMyViewClickListener{

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

}

And that's it.

Kashish Sharma
  • 749
  • 8
  • 18