How do i insert a "onclicklistener" on the imageviews in a cardview?
Context: I extracted frames from a video using ffmpeg, and have images displayed in a cardview, now i need to set a onclicklistener to get the bitmap of the image I clicked.
If i simply applied onClickListener to the view, like so:
view.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
// item clicked
}
});
Will it give me the correct image bitmap that i clicked?
I currently display images in a cardview using an adapter:
Activity
public class PreviewImageActivity extends AppCompatActivity {
private static final String FILEPATH = "filepath";
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gallery);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
TextView tvInstruction=(TextView)findViewById(R.id.tvInstruction) ;
GridLayoutManager lLayoutlLayout = new GridLayoutManager(PreviewImageActivity.this, 4);
RecyclerView rView = (RecyclerView)findViewById(R.id.recycler_view);
rView.setHasFixedSize(true);
rView.setLayoutManager(lLayoutlLayout);
String filePath = getIntent().getStringExtra(FILEPATH);
ArrayList<String> f = new ArrayList<String>();
File dir = new File(filePath);
tvInstruction.setText("Images stored at path "+filePath);
File[] listFile;
listFile = dir.listFiles();
for(File e:listFile)
{
f.add(e.getAbsolutePath());
}
PreviewImageAdapter rcAdapter = new PreviewImageAdapter( f);
rView.setAdapter(rcAdapter);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// handle arrow click here
if (item.getItemId() == android.R.id.home) {
finish(); // close this activity and return to preview activity (if there is any)
}
return super.onOptionsItemSelected(item);
}
}
Adapter
public class PreviewImageAdapter extends RecyclerView.Adapter<PreviewImageAdapter.MyViewHolder> {
private ArrayList<String> paths;
public PreviewImageAdapter( ArrayList<String> paths) {
this.paths = paths;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_gallery, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Bitmap bmp = BitmapFactory.decodeFile(paths.get(position));
holder.ivPhoto.setImageBitmap(bmp);
}
#Override
public int getItemCount() {
return paths.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
private ImageView ivPhoto;
public MyViewHolder(View itemView) {
super(itemView);
ivPhoto = (ImageView) itemView.findViewById(R.id.ivPhoto);
}
}
}
XML
<android.support.v7.widget.CardView
xmlns:card_view="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/card_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
card_view:cardUseCompatPadding="true"
card_view:cardCornerRadius="#dimen/dp4"
android:layout_margin="#dimen/dp8">
<ImageView
android:id="#+id/ivPhoto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:scaleType="centerCrop"
/>
</android.support.v7.widget.CardView>
You should add the OnClickListener in the PreviewImageAdapter onBindViewHolder method, where you have access to the imageview.
holder.ivPhoto.setOnClickListener(new View.OnClickListener())...
another workaround is to implement onClickListener on your ViewHolder class and then switch/case the view ids for different actions like:
class viewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
...
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.v1:
// Your code
break;
case R.id.v2:
// Your Code
break;
}
}
}
Related
I want to create tags using RecyclerView that can be selected to produce results.
What I want to achieve is when I tap on Books TextView on the top-right must change to Books immediately. In my case when I tap on Books it just stays in Art and it replaces Art with Books only when I replace my fragments. I also highlight buttons when clicked (changing border from grey to black) but after changing fragments highlights return back to Art again. Shortly I want to highlight button when clicked and change TextView content based on clicked button text. I partly achieved it by using interfacews but didn't get what I wanted. I provided codes below:
TrendCategoryTagsAdapter.java:
public class TrendCategoryTagsAdapter extends FirestoreRecyclerAdapter<CategorySelection, TrendCategoryTagsAdapter.TrendCategoryTagsHolder> {
Context context;
onCategoryTagClicked onCategoryTagClicked;
int row_index;
public TrendCategoryTagsAdapter(#NonNull FirestoreRecyclerOptions<CategorySelection> options, Context context, com.rajabmammadli.paragrafredesign.Interface.onCategoryTagClicked onCategoryTagClicked) {
super(options);
this.context = context;
this.onCategoryTagClicked = onCategoryTagClicked;
}
#Override
protected void onBindViewHolder(#NonNull final TrendCategoryTagsHolder holder, final int position, #NonNull CategorySelection model) {
holder.categoryNameText.setText(model.getCategoryName());
holder.categoryNameContainer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
row_index = position;
notifyDataSetChanged();
}
});
if (row_index == position) {
holder.categoryNameContainer.setBackground(ContextCompat.getDrawable(context, R.drawable.black_rounded_bg));
onCategoryTagClicked.onTagClick(holder.categoryNameText.getText().toString());
} else {
holder.categoryNameContainer.setBackground(ContextCompat.getDrawable(context, R.drawable.grey_rounded_bg));
}
}
#NonNull
#Override
public TrendCategoryTagsHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.trendcategory_cell, parent, false);
return new TrendCategoryTagsAdapter.TrendCategoryTagsHolder(v);
}
public static class TrendCategoryTagsHolder extends RecyclerView.ViewHolder {
RelativeLayout categoryNameContainer;
TextView categoryNameText;
public TrendCategoryTagsHolder(#NonNull View itemView) {
super(itemView);
categoryNameContainer = itemView.findViewById(R.id.categoryNameContainer);
categoryNameText = itemView.findViewById(R.id.categoryNameText);
}
}
}
trendcategory_cell.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp">
<RelativeLayout
android:id="#+id/categoryNameContainer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/grey_rounded_bg">
<TextView
android:id="#+id/categoryNameText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="#font/gilroyregular"
android:padding="15dp"
android:text="categoryname"
android:textColor="#android:color/black" />
</RelativeLayout>
</RelativeLayout>
TrendingFragment.java:
public class TrendingFragment extends Fragment implements onCategoryTagClicked {
RecyclerView trendingCategoryRV;
TextView noPostTV, selectedCategoryText;
FirebaseFirestore db = FirebaseFirestore.getInstance();
CollectionReference categoryRef;
String selectedCategory = "Art";
TrendCategoryTagsAdapter trendCategoryTagsAdapter;
public TrendingFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_trending, container, false);
trendPostRV = view.findViewById(R.id.trendPostRV);
trendingCategoryRV = view.findViewById(R.id.trendingCategoryRV);
noPostTV = view.findViewById(R.id.noPostTV);
selectedCategoryText = view.findViewById(R.id.selectedCategoryText);
selectedCategoryText.setText(selectedCategory);
setUpTrendCategoryTagsRV();
setUpTrendingPostRV();
// Inflate the layout for this fragment
return view;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
trendCategoryTagsAdapter.startListening();
}
#Override
public void onDestroyView() {
super.onDestroyView();
trendCategoryTagsAdapter.stopListening();
}
private void setUpTrendCategoryTagsRV() {
categoryRef = db.collection("Categories");
Query query = categoryRef.orderBy("categoryName", Query.Direction.ASCENDING);
FirestoreRecyclerOptions<CategorySelection> options = new FirestoreRecyclerOptions.Builder<CategorySelection>()
.setQuery(query, CategorySelection.class)
.build();
trendCategoryTagsAdapter = new TrendCategoryTagsAdapter(options, getContext(), this);
trendingCategoryRV.setNestedScrollingEnabled(false);
final LinearLayoutManager trendingTagsLM = new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false);
trendingCategoryRV.setLayoutManager(trendingTagsLM);
trendingCategoryRV.setAdapter(trendCategoryTagsAdapter);
trendCategoryTagsAdapter.notifyDataSetChanged();
}
#Override
public void onTagClick(String categoryName) {
selectedCategory = categoryName;
}
}
Any help will be appreciated. Thanks in advance
Now that I got my RecyclerView working, and I can communicate between my Activity and my Adapter, I wanted to create an OnClickListener, which I did with success.
But somehow, it only works on buttons, not on other items.
In the Layout of my RecyclerView, I am having the following:
<TextView
android:id="#+id/tvWebsite"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clickable="true"
android:singleLine="true"
android:text="tvWebsite" />
<Button
android:id="#+id/btnWebsite"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button" />
So the TextView is clickable. The button is too, but that is default behaviour.
In my Adapter class, I am having the following:
public class CompanyAdapter extends RecyclerView.Adapter<CompanyAdapter.ViewHolder>
{
private Context mContext;
private ArrayList<Company> companyname;
public CompanyAdapter (Context context, ArrayList<Company> list)
{
this.mContext = context;
companyname = list;
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener
{
TextView tvCompanyName;
TextView tvVatID;
TextView tvPostalCode;
TextView tvPhoneNumber;
TextView tvProprietorName;
TextView tvWebsite;
TextView tvEmail;
TextView tvFirstAvailableDate;
TextView tvFirstAvailableTimeBlock;
TextView tvAvailableInPostalCode;
TextView tvAvailableNumberOfPersons;
Button btnWebsite;
public ViewHolder(#NonNull final View itemView)
{
super(itemView);
tvCompanyName = itemView.findViewById(R.id.tvCompanyName);
tvVatID = itemView.findViewById(R.id.tvVatNo);
tvPostalCode = itemView.findViewById(R.id.tvPostalCode);
tvPhoneNumber = itemView.findViewById(R.id.tvPhoneNumber);
tvProprietorName = itemView.findViewById(R.id.tvProprietorName);
tvWebsite = itemView.findViewById(R.id.tvWebsite);
tvEmail = itemView.findViewById(R.id.tvEmail);
tvFirstAvailableDate = itemView.findViewById(R.id.tvFrstAvailableDate);
tvFirstAvailableTimeBlock = itemView.findViewById(R.id.tvFirstAvailableTimeBlock);
tvAvailableInPostalCode = itemView.findViewById(R.id.tvPostalCodeAvailable);
tvAvailableNumberOfPersons = itemView.findViewById(R.id.tvAvailableNumberOfPersons);
btnWebsite = itemView.findViewById(R.id.btnWebsite);
tvWebsite.setClickable(true);
tvWebsite.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view) {
if (mContext instanceof SearchForHelp) {
((SearchForHelp) mContext).ClickWebsite();
}
}
});
btnWebsite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mContext instanceof SearchForHelp) {
((SearchForHelp) mContext).ClickButton();
}
}
});
}
#Override
public void onClick(View view) {
}
}
#NonNull
#Override
public CompanyAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_items, viewGroup, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull CompanyAdapter.ViewHolder viewHolder, int i) {
viewHolder.itemView.setTag(companyname.get(i));
viewHolder.tvCompanyName.setText(companyname.get(i).getStrCompanyName());
viewHolder.tvVatID.setText(companyname.get(i).getStrVatID());
viewHolder.tvPostalCode.setText(companyname.get(i).getStrPostalCode());
viewHolder.tvPhoneNumber.setText(companyname.get(i).getStrPhoneNumber());
viewHolder.tvProprietorName.setText(companyname.get(i).getStrProprietorName());
viewHolder.tvWebsite.setText(companyname.get(i).getStrWebsite());
viewHolder.tvEmail.setText(companyname.get(i).getStrEmail());
viewHolder.tvFirstAvailableDate.setText(companyname.get(i).getStrFirstAvailableDate());
viewHolder.tvFirstAvailableTimeBlock.setText(companyname.get(i).getStrFirstAvailableTimeBlock());
viewHolder.tvAvailableInPostalCode.setText(companyname.get(i).getStrAvailableInPostalCode());
viewHolder.tvAvailableNumberOfPersons.setText(companyname.get(i).getStrAvailableNumberOfPersons());
viewHolder.tvWebsite.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view) {
//Toast.makeText(getClass(),"Test",Toast.LENGTH_SHORT).show();
//viewHolder.tvCompanyName.setText("Changed");
}
});
}
#Override
public int getItemCount() {
return companyname.size();
}
}
And finally, in my Activity:
public void ClickButton()
{
Toast.makeText(getApplicationContext(),"Clicked on Button",Toast.LENGTH_LONG).show();
}
public void ClickWebsite()
{
Toast.makeText(getApplicationContext(),"Clicked on TextView",Toast.LENGTH_LONG).show();
}
Please note, that
tvWebsite.setClickable(true);
has been added to see if it made any difference, but it didn't.
If I click on the button, it toastes "Clicked on button", but if I click on the TextView, nothing happens.
So what do I miss in order to make the TextView tvWebsite clickable?
There is no need for tvWebsite.setClickable(true);
And you are setting click listener for tvWebsite in onBindViewHolder callback again.
You need to remove this code from onBindViewHolder method.
viewHolder.tvWebsite.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view) {
//Toast.makeText(getClass(),"Test",Toast.LENGTH_SHORT).show();
//viewHolder.tvCompanyName.setText("Changed");
}
});
---------rest is fine.
I'm a beginner and I'm trying to build a simple voice recorder app. I've already posted on the website concerning the access of external storage. This problem is now solved but I've an another one concerning my RecyclerView.
I've followed a tutorial online in order to detect which view is clicked and play the audio accordingly (I use my RecyclerView to display all the recording files just created). Here's the tutorial in question : https://www.youtube.com/watch?v=ZXoGG2XTjzU
The problem is, the 'OnNoteClick' does absolutely nothing. How can I fix this ?
I created an interface with a function 'OnNoteClick' attached to it. I implemented this function in mainactivity.java. Basically, I've followed the tutorial.
\\\ Adapter Code
private OnNoteListener mOnNoteListener;
...
public RecyclerViewAdapter(#NonNull ArrayList<String> text, Context context, OnNoteListener onNoteListener) {
Text = text;
this.context = context;
this.mOnNoteListener = onNoteListener;
}
...
public ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.cardview, viewGroup, false);
ViewHolder holder = new ViewHolder(view, mOnNoteListener);
return holder;
}
...
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView textView;
CardView ParentLayout;
OnNoteListener onNoteListener;
public ViewHolder(#NonNull View itemView, OnNoteListener onNoteListener) {
super(itemView);
textView = itemView.findViewById(R.id.cardtext);
ParentLayout = itemView.findViewById(R.id.cardview);
this.onNoteListener = onNoteListener;
ParentLayout.setOnClickListener(this);
}
#Override
public void onClick(View v) {
onNoteListener.onNoteClick(getAdapterPosition());
}
}
public interface OnNoteListener{
void onNoteClick(int position);
}
}
...
\\\ MainActivityCode
public class FileAndDirectoryActivity extends AppCompatActivity implements RecyclerViewAdapter.OnNoteListener {
...
private void initRecyclerView() {
RecyclerView recyclerView = findViewById(R.id.recyclerview);
RecyclerViewAdapter adapter = new RecyclerViewAdapter(mNames, this, this);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
}
...
#Override
public void onNoteClick(int position) {
Toast.makeText(this, "Good News : I'm working", Toast.LENGTH_SHORT).show();
}
}
...
I expect the app to show a message reading "I'm working" or something like that but in reality, when i touch the cardview, nothing happens.
Your problem is in:
public void onBindViewHolder(#NonNull ViewHolder holder, int i) {
holder.textView.setText(Text.get(i));
holder.ParentLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: Click on this card !");
}
});
}
You set a new click listener on ParentLayout so it overwrites click listener that you set in constructor. Try it without and it should work:
public void onBindViewHolder(#NonNull ViewHolder holder, int i) {
holder.textView.setText(Text.get(i));
}
Change your Adapter to below code and also Make sure you are fetching correct id of cardView
private OnNoteListener mOnNoteListener;
...
public RecyclerViewAdapter(#NonNull ArrayList<String> text, Context context, OnNoteListener onNoteListener) {
Text = text;
this.context = context;
this.mOnNoteListener = onNoteListener;
}
...
public ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(context).inflate(R.layout.cardview, viewGroup, false);
ViewHolder holder = new ViewHolder(view);
return holder;
}
...
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView textView;
CardView ParentLayout;
public ViewHolder(#NonNull View itemView) {
super(itemView);
textView = itemView.findViewById(R.id.cardtext);
ParentLayout = itemView.findViewById(R.id.cardview);
ParentLayout.setOnClickListener(this);
}
#Override
public void onClick(View v) {
mOnNoteListener.onNoteClick(getAdapterPosition());
}
}
public interface OnNoteListener{
void onNoteClick(int position);
}
}
No need to pass listener on ViewHolder constructor, because you have mOnNoteListener as global varible.
Just create setonclicklistener of view in onBind method. And call interface method on that.
Like
mOnNoteListener.onNoteClick(pos);
pos integer as position got in onBind method
Here i given you clear explanation,
Create one common Interface, named as CustomItemClickListenere
public interface CustomItemClickListenere {
public void onItemClick(View v, int position); }
Change your adapter class like below,
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
private ArrayList<AddSingleItemList> data;
private Context mContext;
private CustomItemClickListenere listener;
public RecyclerViewAdapter(Context mContext, ArrayList<AddSingleItemList> data, CustomItemClickListenere listener) {
this.data = data;
this.mContext = mContext;
this.listener = listener;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View mView = LayoutInflater.from(parent.getContext()).inflate(R.layout.items_list_single_item, parent, false);
final ViewHolder mViewHolder = new ViewHolder(mView);
mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
listener.onItemClick(v, mViewHolder.getPosition());
}
});
return mViewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.itemTitle.setText(Html.fromHtml(data.get(position).getTitle()));
}
#Override
public int getItemCount() {
return data.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView itemTitle;
public CardView cardView;
ViewHolder(View v) {
super(v);
itemTitle = (TextView) v.findViewById(R.id.person_name);
cardView = (CardView) v.findViewById(R.id.cv);
}
}
}
adapter's xml item_list_single_item :
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/cv"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp">
<TextView
android:id="#+id/person_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:textSize="12sp" />
</RelativeLayout>
</android.support.v7.widget.CardView>
Here i have created on Pojo class for setting static items on Recyclerview, named as AddSingleItemList :
public class AddSingleItemList {
private String title;
long id;
/**
*
* #param id
* #param title
*/
public AddSingleItemList(long id, String title) {
this.id = id;
this.title = title;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
}
Update you RecyclerViewActivity like below :
public class RecyclerViewActivity extends AppCompatActivity {
RecyclerView itemsList;
RecyclerViewAdapter adapter;
ArrayList<AddSingleItemList> data = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
itemsList = (RecyclerView) findViewById(R.id.items_list);
LinearLayoutManager llm = new LinearLayoutManager(this);
itemsList.setLayoutManager(llm);
itemsList.setHasFixedSize(true);
//Add you items into the Recyclerview list
data.add(new AddSingleItemList(1, "First Item"));
data.add(new AddSingleItemList(2, "Second Item"));
adapter = new RecyclerViewAdapter(this, data, new CustomItemClickListenere() {
#Override
public void onItemClick(View v, int position) {
Log.d("RecyclerViewActivity", "clicked position:" + position);
Toast.makeText(RecyclerViewActivity.this, "Good News : I'm working", Toast.LENGTH_SHORT).show();
// do what ever you want to do with it
}
});
itemsList.setAdapter(adapter);
}
}
Finally you will get result as you raised in your question,
I am programming a simple game in android and I encountered a problem with recyclerview. I need help please , tnx :)
I have an activity that create an arrayList and add my data to it then pass it to my recyclerview's adapter . In the adapter I write code that user can't select more than an image. Now the problem is there when I select first item and then scroll recyclerview I see that one of the last three items is selected. And this case happen for only fist line items and last three items too.
What can I do for that ?
My activity :
public class page_register extends AppCompatActivity {
Activity _A;
Context _C;
private RecyclerView recyclerView1, recyclerView2;
private AdsAdapter adapter1;
private Avatar2Adapter adapter2;
private ArrayList<Ads> adsArrayList;
TextView Tv1, Tv2;
EditText ET1, ET2;
Button BT_First, BT_Second;
ImageButton BT_Back;
ImageView img_first, img_second;
CardView cardView1, cardView2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.page_register);
M_UI.SetOffKeyboard(this);
M_Font.Initial(this);
_A = this;
_C = this;
Initial();
adsArrayList = new ArrayList<>();
adsArrayList.add(new Ads(R.drawable.a1));
adsArrayList.add(new Ads(R.drawable.a2));
adsArrayList.add(new Ads(R.drawable.a3));
adsArrayList.add(new Ads(R.drawable.a4));
adsArrayList.add(new Ads(R.drawable.a5));
adsArrayList.add(new Ads(R.drawable.a6));
adsArrayList.add(new Ads(R.drawable.a7));
adsArrayList.add(new Ads(R.drawable.a8));
adsArrayList.add(new Ads(R.drawable.a9));
adsArrayList.add(new Ads(R.drawable.a10));
adsArrayList.add(new Ads(R.drawable.a11));
adsArrayList.add(new Ads(R.drawable.a12));
adsArrayList.add(new Ads(R.drawable.a13));
adsArrayList.add(new Ads(R.drawable.a14));
adsArrayList.add(new Ads(R.drawable.a15));
adsArrayList.add(new Ads(R.drawable.a16));
adsArrayList.add(new Ads(R.drawable.a17));
adsArrayList.add(new Ads(R.drawable.a18));
adsArrayList.add(new Ads(R.drawable.a19));
adsArrayList.add(new Ads(R.drawable.a20));
adsArrayList.add(new Ads(R.drawable.a21));
//--------------------------------------------
adapter1 = new AdsAdapter(adsArrayList, this, _C, _A, recyclerView1, 0);
adapter2 = new Avatar2Adapter(adsArrayList, this, _C, _A, recyclerView2, 0);
RecyclerView.LayoutManager layoutManager1 = new GridLayoutManager(_C, 3);
RecyclerView.LayoutManager layoutManager2 = new GridLayoutManager(_C, 3);
recyclerView1.setLayoutManager(layoutManager1);
recyclerView2.setLayoutManager(layoutManager2);
recyclerView1.setAdapter(adapter1);
recyclerView2.setAdapter(adapter2);
}
public void Initial() {
recyclerView1 = (RecyclerView) findViewById(R.id.recycler_view1);
recyclerView2 = (RecyclerView) findViewById(R.id.recycler_view2);
}
}
and my adapter :
public class AdsAdapter extends RecyclerView.Adapter<AdsAdapter.AdsViewHolder> {
private ArrayList<Ads> dataList;
Context _C1;
Activity _A1;
RecyclerView r;
int SelectedPos = 0;
int id_prev;
CardView CV_Prev = null;
public AdsAdapter(ArrayList<Ads> dataList, FragmentActivity activity, Context _C, Activity _A, RecyclerView recyclerView, int i) {
this.dataList = dataList;
_A1 = _A;
_C1 = _C;
r = recyclerView;
}
#Override
public AdsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
final LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
final View view = layoutInflater.inflate(R.layout.avatars, parent, false);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View SelectCardView) {
try {
if (CV_Prev != null) {
CV_Prev.findViewById(R.id.img_select).setVisibility(View.INVISIBLE);
}
SelectCardView.findViewById(R.id.img_select).setVisibility(View.VISIBLE);
CV_Prev = (CardView) SelectCardView;
} catch (Exception e) {
Toast.makeText(_C1, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
return new AdsViewHolder(view);
}
#Override
public void onBindViewHolder(AdsViewHolder holder, int position) {
holder.CV_item.setTag(position);
//------------------------------------------------------------------
holder.img_avatar.setImageResource(dataList.get(position).getImage());
}
#Override
public int getItemCount() {
return dataList.size();
}
class AdsViewHolder extends RecyclerView.ViewHolder {
ImageView img_avatar;
CardView CV_item;
AdsViewHolder(View itemView) {
super(itemView);
//-----------------------------------------------------------
img_avatar = (ImageView) itemView.findViewById(R.id.img_avatar);
CV_item = (CardView) itemView.findViewById(R.id.cardView);
}
}
}
my view :
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/cardView"
android:layout_width="100dp"
android:layout_height="100dp"
android:background="#00ffffff"
android:layoutDirection="ltr"
android:paddingLeft="5dp"
android:paddingRight="5dp"
card_view:cardBackgroundColor="#B2EBF2"
card_view:cardCornerRadius="5dp"
card_view:cardElevation="5dp"
card_view:cardUseCompatPadding="true">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/img_avatar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#00ffffff"
card_view:srcCompat="#drawable/a1" />
<ImageView
android:id="#+id/img_select"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:visibility="invisible"
card_view:srcCompat="#mipmap/ic_check_circle_black_48dp" />
</RelativeLayout>
</android.support.v7.widget.CardView>
my model :
public class Ads {
private int image;
public Ads(int image)
{
this.image = image;
}
public void setImage(int image) {this.image = image;}
public int getImage() {return image;}
}
below image shows my mean :
*** I tried to set id for each card and image and selecting them by their id but that didn't help too.
This happens because recycler view recycles the view in OnBindViewHolder.To solve this.
create a global variable to store the clicked position.
private mItemSelected=-1;
Then inside viewholder add the clickListener and onClick store the position of the clicked item.
class AdsViewHolder extends RecyclerView.ViewHolder {
ImageView img_avatar;
CardView CV_item;
AdsViewHolder(View itemView) {
super(itemView);
//-----------------------------------------------------------
img_avatar = (ImageView) itemView.findViewById(R.id.img_avatar);
CV_item = (CardView) itemView.findViewById(R.id.cardView);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mItemSelected=getAdapterPosition();
notifyDataSetChanged();
}
});
}
}
And in inside OnBindViewHolder,
if(mItemSelected==position){
//code for image selected.
holder.CV_item.setVisibility(View.VISIBLE);
}else{
//code for image unselected.
holder.CV_item.setVisibility(View.INVISIBLE);
}
Also remove the click listener that has been added in the createViewholder instead add it inside the constructor of AdsViewHolder as added above.
EDIT:Check this updated code.Hope it helps you.
public class AdsAdapter extends RecyclerView.Adapter<AdsAdapter.AdsViewHolder> {
private ArrayList<Ads> dataList;
Context _C1;
Activity _A1;
RecyclerView r;
int SelectedPos = 0;
int id_prev;
CardView CV_Prev = null;
private int mItemSelected=-1;
public AdsAdapter(ArrayList<Ads> dataList, FragmentActivity activity, Context _C, Activity _A, RecyclerView recyclerView, int i) {
this.dataList = dataList;
_A1 = _A;
_C1 = _C;
r = recyclerView;
}
#Override
public AdsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
final LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
final View view = layoutInflater.inflate(R.layout.avatars, parent, false);
return new AdsViewHolder(view);
}
#Override
public void onBindViewHolder(AdsViewHolder holder, int position) {
holder.CV_item.setTag(position);
holder.img_avatar.setImageResource(dataList.get(position).getImage());
if(mItemSelected==position){
//code for image selected.
holder.CV_item.setVisibility(View.VISIBLE);
}else{
//code for image unselected.
holder.CV_item.setVisibility(View.INVISIBLE);
}
}
#Override
public int getItemCount() {
return dataList.size();
}
class AdsViewHolder extends RecyclerView.ViewHolder {
ImageView img_avatar;
CardView CV_item;
AdsViewHolder(View itemView) {
super(itemView);
//-----------------------------------------------------------
img_avatar = (ImageView) itemView.findViewById(R.id.img_avatar);
CV_item = (CardView) itemView.findViewById(R.id.cardView);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mItemSelected=getAdapterPosition();
notifyDataSetChanged();
}
});
}
}
}
Replace this code
if (CV_Prev != null && CV_Prev.findViewById(R.id.img_select).getVisibility() == View.VISIBLE) {
CV_Prev.findViewById(R.id.img_select).setVisibility(View.INVISIBLE);
}
if(SelectCardView.findViewById(R.id.img_select).getVisibility() == View.INVISIBLE)
SelectCardView.findViewById(R.id.img_select).setVisibility(View.VISIBLE);
or you can create a global variable to store the clicked position and change its Visibility after second click
See if this helps: https://stackoverflow.com/a/46641850/4469112 I just explained how to properly set the on click listeners to recycler view's adapter and view holders. The important part is to set the listener to the view holder (and no directly to the view), and then to let the view holder to set itself as listener to the passed view. Remember the view is recycled and the content is binded to it at runtime (when you scroll in your case), that's why you're seeing the selection 'transferred' to the other items.
This question already has answers here:
RecyclerView onClick
(49 answers)
Closed 6 years ago.
Hello I made a recycler view and I don't know how to configure for Onclick function on these items which can open another activity name (xyz.xml)
Main Activity.java
public class MainActivity extends AppCompatActivity {
List<GetDataAdapter> GetDataAdapter1;
RecyclerView recyclerView;
RecyclerView.LayoutManager recyclerViewlayoutManager;
RecyclerView.Adapter recyclerViewadapter;
String GET_JSON_DATA_HTTP_URL = "http://platinummun.com/android_login_api/ImageJsonData.php";
String JSON_IMAGE_TITLE_NAME = "image_title";
String JSON_IMAGE_URL = "image_url";
JsonArrayRequest jsonArrayRequest ;
RequestQueue requestQueue ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GetDataAdapter1 = new ArrayList<>();
recyclerView = (RecyclerView) findViewById(R.id.recyclerview1);
recyclerView.setHasFixedSize(true);
recyclerViewlayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(recyclerViewlayoutManager);
JSON_DATA_WEB_CALL();
}
public void JSON_DATA_WEB_CALL(){
jsonArrayRequest = new JsonArrayRequest(GET_JSON_DATA_HTTP_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
JSON_PARSE_DATA_AFTER_WEBCALL(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
}
public void JSON_PARSE_DATA_AFTER_WEBCALL(JSONArray array){
for(int i = 0; i<array.length(); i++) {
GetDataAdapter GetDataAdapter2 = new GetDataAdapter();
JSONObject json = null;
try {
json = array.getJSONObject(i);
GetDataAdapter2.setImageTitleNamee(json.getString(JSON_IMAGE_TITLE_NAME));
GetDataAdapter2.setImageServerUrl(json.getString(JSON_IMAGE_URL));
} catch (JSONException e) {
e.printStackTrace();
}
GetDataAdapter1.add(GetDataAdapter2);
}
recyclerViewadapter = new RecyclerViewAdapter(GetDataAdapter1, this);
recyclerView.setAdapter(recyclerViewadapter);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.android_examples.recyclerviewimagelistview_android_examplescom.MainActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerview1"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</RelativeLayout>
recyclerview_items.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/cardview1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
card_view:cardElevation="3dp"
card_view:contentPadding="3dp"
card_view:cardCornerRadius="3dp"
card_view:cardMaxElevation="3dp"
>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<com.android.volley.toolbox.NetworkImageView
android:id="#+id/VollyNetworkImageView1"
android:layout_width="150dp"
android:layout_height="100dp"
android:src="#mipmap/ic_launcher"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Image Name"
android:id="#+id/textView_item"
android:layout_centerVertical="true"
android:layout_toRightOf="#+id/VollyNetworkImageView1"
android:layout_toEndOf="#+id/VollyNetworkImageView1"
android:layout_marginLeft="20dp"/>
</RelativeLayout>
</android.support.v7.widget.CardView>
Check image here
Please help me to do it
You can try this
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
private ArrayList<String> list;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView text;
public String result;
public MyViewHolder(View view) {
super(view);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//TODO startintent
}
});
}
}
public MyAdapter(ArrayList<String> list) {
this.list = list;
}
// Create new views (invoked by the layout manager)
#Override
public MyAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
// create a new view
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.view, parent, false);
MyViewHolder vh = new MyViewHolder(v);
return vh;
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
// - get element from your dataset at this position
// - replace the contents of the view with that element
holder.result = list.get(position);
holder.text.setText(list.get(position).getContentTitle());
}
#Override
public int getItemCount() {
return list.size();
}
}
You can use ItemClickSupport class to attach a listener to items in your RecyclerView
In your Adapter class,
you can implement click listener like this
#Override
public void onBindViewHolder(final YourHolder holder, final int position) {
holder.cardView1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context,NextActivity.class);
//if you want to pass data
intent.putExtra("hi",list.get(position).getHi());
startActivity(intent);
}
});
}
You can create an Interface in your adapter for items click.
For example:
interface ItemClickListener
{
void onItemClicked();
}
View Holder:
public static class ItemViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private YourModel mItem;
private ItemClickListener mItemListener;
public ItemViewHolder(View itemView, ItemClickListener listener) {
super(itemView);
ButterKnife.bind(this, itemView);
mItemListener = listener;
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.view_id:
mItemListener.onItemClicked(); // You can send any field or model as a param here.
break;
default:
break;
}
}
}
After that you can implement this interface in your Activity/Fragment and can write code for click event.