I am trying to figure out how I can determine which image a user has click on when the images are all in a FrameLayout and the view is inflated with an Adapter
The setItemClickListener for the Adapter is below: (The pos works in determining which element in the array was click, so first item in the list gets 0 and so on...):
holder.setItemClickListener(new ItemClickListener() {
@Override
public void onItemClick(View v, int pos) {
switch (pos) {
case 0:
// First item was clicked
break;
case 1:
// Second item was clicked
break;
}
Toast.makeText(v.getContext(), "Clicked list item = " + pos, Toast.LENGTH_SHORT).show();
}
});
The following is the layout that holds the list of items:
<FrameLayout 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:id="@+id/rootView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<ImageView
android:layout_width="match_parent"
android:layout_height="180dp"
android:layout_centerHorizontal="true"
app:srcCompat="@drawable/background" />
<ImageView
android:id="@+id/awayTeam"
android:layout_width="160dp"
android:layout_height="150dp"
android:layout_gravity="top|left" />
<ImageView
android:id="@+id/homeTeam"
android:layout_width="160dp"
android:layout_height="150dp"
android:layout_gravity="top|right"
android:scaleX="-1" />
</androidx.cardview.widget.CardView>
</FrameLayout>
</LinearLayout>
How would I be able to determine which ImageView the user clicks in the position in the list?
class GameViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private ItemClickListener mListener;
private ImageView awayTeamImageView, homeTeamImageView;
public GameViewHolder(View itemView) {
super(itemView);
awayTeamImageView = itemView.findViewById(R.id.awayTeam);
homeTeamImageView = itemView.findViewById(R.id.homeTeam);
itemView.setOnClickListener(this);
}
Override
public void onClick(View v) {
this.mListener.onItemClick(v, getLayoutPosition());
}
public void setItemClickListener(ItemClickListener listener) {
this.mListener = listener;
}
}
Try with the following code
holder.setItemClickListener(new ItemClickListener() {
@Override
public void onItemClick(View v, int pos) {
switch (v.getId()) {
case R.id.awayTeam:
// click on image awayTeam
break;
case R.id.homeTeam:
// click on image homeTeam
break;
}
Toast.makeText(v.getContext(), "Clicked list item = " + pos, Toast.LENGTH_SHORT).show();
}
});
// Also update your holder code
public GameViewHolder(@NonNull View itemView) {
super(itemView);
itemView.setOnClickListener(this);
awayTeamImageView = itemView.findViewById(R.id.awayTeam);
homeTeamImageView = itemView.findViewById(R.id.homeTeam);
awayTeamImageView.setOnClickListener(this);
homeTeamImageView.setOnClickListener(this);
}