I can't click on items in RecyclerView. For example, as shown in the code, I gave Tittle a click feature, but I can't click right now. In the same way I gave deleteimage a click feature, but I can't click. What do I need to do to make the items clickable? Where is the problem? I can't click on the items in RecyclerView, that's the problem.
XML Source Code:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/white"
android:orientation="horizontal">
<ImageView
android:id="#+id/productImage"
android:layout_width="80dp"
android:layout_height="80dp"
android:src="#drawable/roomlocation" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical">
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="3dp"
android:layout_marginTop="9dp"
android:text="productAdi"
android:textSize="19dp"
android:clickable="true"
android:textStyle="bold" />
<TextView
android:id="#+id/productDescription"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="3dp"
android:layout_marginTop="3dp"
android:text="Cihaza ait eklenmiş odalar"
android:textSize="14dp"
android:textStyle="italic" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:orientation="vertical">
<ImageView
android:id="#+id/deleteproduct"
android:layout_width="25dp"
android:layout_height="25dp"
android:layout_marginRight="10dp"
android:layout_marginBottom="5dp"
android:clickable="true"
android:src="#drawable/ic_delete_yellow" />
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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="stechome.berkeylen.firebasedatabase.RoomsActivity">
<include
android:id="#+id/toolbar"
layout="#layout/toolbar" />
<android.support.v7.widget.RecyclerView
android:id="#+id/rvRooms"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v7.widget.RecyclerView>
</android.support.constraint.ConstraintLayout>
RecyclerView Class Source:
public class RoomsAdapter extends RecyclerView.Adapter<RoomsAdapter.MyViewHolder> {
DatabaseReference ref = mDatabase.child("0").child("Rooms");
public class MyViewHolder extends RecyclerView.ViewHolder {
public MyViewHolder(View view) {
super(view);
productImage = (ImageView)
itemView.findViewById(R.id.productImage);
title = (TextView) view.findViewById(R.id.title);
deleteImage = (ImageView) view.findViewById(R.id.deleteproduct);
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
String data = snapshot.getValue(String.class);
Rooms.add(data);
title.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = 0;
position = getAdapterPosition();
if (getAdapterPosition() == position){
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference().child("0");
rootRef.child("titles").child("0").child("places").setValue(Rooms.get(position));
}
}
});
}
deleteImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (v == deleteproduct) {
deleteproduct(getLayoutPosition());
}
}
});
}
Set click listeners on recycler items by overriding onBindViewHolder method of adapter:
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.myTextView.setOnClickListener(...);
}
here you can find an example: https://developer.android.com/guide/topics/ui/layout/recyclerview
I had the same problem. After trying many things, the only one that worked was to add an atribute on the XML of the item layout:
onClick = the name of the method / function you want to trigger
Related
I want to show a popup menu for each item of a RecyclerView when a button is clicked.
My Adapter:
public class SearchResultRecyclerViewAdapter extends RecyclerView.Adapter<SearchResultRecyclerViewAdapter.ViewHolder> {
public SearchResultRecyclerViewAdapter(ArrayList<BookModel> bookModels, Context context) {
this.bookModels = bookModels;
this.context = context;
}
ArrayList<BookModel> bookModels;
Context context;
#NonNull
#NotNull
#Override
public ViewHolder onCreateViewHolder(#NonNull #NotNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_book,parent,false);
ViewHolder holder = new ViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Log.d("aa", bookModels.get(position).getThumbnailLink());
Glide.with(context)
.asBitmap()
.load(bookModels.get(position).getThumbnailLink())
.into(holder.coverImage);
holder.name.setText(bookModels.get(position).getName());
holder.author.setText(bookModels.get(position).getAuthor());
holder.category.setText(bookModels.get(position).getCategories().toString());
holder.maturity.setText(bookModels.get(position).getMaturityRating());
holder.desc.setText(bookModels.get(position).getDesc());
holder.option.setOnClickListener(new View.OnClickListener() { ///////////// here
#Override
public void onClick(View v) {
//show popup
Log.d("ItemOption","Clicked");
}
});
if (position+1 == bookModels.size()){
holder.divider.setVisibility(View.GONE);
}
}
#Override
public int getItemCount() {
return bookModels.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
RoundedImageView coverImage;
TextView name;
TextView author;
TextView desc;
TextView category;
TextView maturity;
ImageView divider;
Button option;
RelativeLayout root;
public ViewHolder(#NonNull #NotNull View itemView) {
super(itemView);
coverImage = itemView.findViewById(R.id.cover_book_item_imageview);
name = itemView.findViewById(R.id.name_book_item_textview);
author = itemView.findViewById(R.id.author_book_item_textview);
desc = itemView.findViewById(R.id.desc_book_item_textview);
category = itemView.findViewById(R.id.category_book_item_textview);
maturity = itemView.findViewById(R.id.maturity_book_item_textview);
divider = itemView.findViewById(R.id.divider_book_item_imageview);
option = itemView.findViewById(R.id.option_book_item_button);
root = itemView.findViewById(R.id.root);
}
}
}
My item Layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/root"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<androidx.cardview.widget.CardView
android:id="#+id/cover_book_item_cardview"
android:layout_width="#dimen/_81sdp"
android:layout_height="#dimen/_124sdp"
android:layout_margin="#dimen/_15sdp"
app:cardCornerRadius="#dimen/_8sdp"
android:elevation="#dimen/_5sdp">
<com.makeramen.roundedimageview.RoundedImageView
android:id="#+id/cover_book_item_imageview"
android:layout_height="match_parent"
android:layout_width="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:src="#drawable/testcover"
android:scaleType="fitXY"
app:riv_corner_radius="#dimen/_5sdp"/>
</androidx.cardview.widget.CardView>
<TextView
android:id="#+id/name_book_item_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="name"
android:layout_marginTop="#dimen/_20sdp"
android:layout_alignStart="#id/cover_book_item_cardview"
android:layout_marginStart="#dimen/_90sdp"
android:fontFamily="#font/yanonekaffeesatz_medium"
android:layout_alignLeft="#id/cover_book_item_cardview"
android:layout_marginLeft="#dimen/_90sdp"
android:textSize="#dimen/_18sdp"
android:textColor="#color/light_black"
/>
<TextView
android:id="#+id/author_book_item_textview"
android:textSize="#dimen/_13sdp"
android:fontFamily="#font/yanonekaffeesatz_medium"
android:layout_marginTop="#dimen/_1sdp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/name_book_item_textview"
android:text="author"
android:layout_alignLeft="#id/cover_book_item_cardview"
android:layout_marginLeft="#dimen/_90sdp"
android:layout_alignStart="#id/cover_book_item_cardview"
android:layout_marginStart="#dimen/_90sdp"/>
<TextView
android:id="#+id/desc_book_item_textview"
android:layout_width="#dimen/_190sdp"
android:layout_height="#dimen/_40sdp"
android:layout_below="#id/name_book_item_textview"
android:width="#dimen/_60sdp"
android:layout_alignLeft="#id/cover_book_item_cardview"
android:layout_marginLeft="#dimen/_90sdp"
android:layout_alignStart="#id/cover_book_item_cardview"
android:layout_marginStart="#dimen/_90sdp"
android:layout_marginTop="#dimen/_30sdp"
android:textColor="#color/light_black"
android:text="desc"
android:fontFamily="#font/yanonekaffeesatz_medium"/>
<LinearLayout
android:id="#+id/holder_book_item_linearlayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_below="#id/name_book_item_textview"
android:layout_alignLeft="#id/cover_book_item_cardview"
android:layout_marginLeft="#dimen/_90sdp"
android:layout_alignStart="#id/cover_book_item_cardview"
android:layout_marginStart="#dimen/_90sdp">
<TextView
android:id="#+id/category_book_item_textview"
android:textColor="#color/white"
android:fontFamily="#font/yanonekaffeesatz_medium"
android:background="#drawable/rounded_rectangle_90"
android:backgroundTint="#color/yellow"
android:padding="#dimen/_3sdp"
android:layout_marginTop="#dimen/_72sdp"
android:text="category"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<TextView
android:id="#+id/maturity_book_item_textview"
android:textColor="#color/white"
android:fontFamily="#font/yanonekaffeesatz_medium"
android:background="#drawable/rounded_rectangle_90"
android:backgroundTint="#color/light_black"
android:padding="#dimen/_3sdp"
android:layout_marginTop="#dimen/_72sdp"
android:text="maturity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="#dimen/_5sdp"/>
</LinearLayout>
<androidx.appcompat.widget.AppCompatButton
android:id="#+id/option_book_item_button"
android:layout_width="#dimen/_20sdp"
android:layout_height="#dimen/_20sdp"
android:background="#drawable/ic_more"
android:backgroundTint="#color/light_black"
android:layout_alignLeft="#id/cover_book_item_cardview"
android:layout_marginLeft="#dimen/_260sdp"
android:layout_alignStart="#id/cover_book_item_cardview"
android:layout_marginStart="#dimen/_260sdp"
android:layout_marginTop="#dimen/_23sdp"/>
<ImageView
android:id="#+id/divider_book_item_imageview"
android:layout_width="#dimen/_200sdp"
android:layout_height="1dp"
android:background="#DFDFDF"
android:layout_below="#id/holder_book_item_linearlayout"
android:layout_marginTop="#dimen/_15sdp"
android:layout_centerHorizontal="true"/>
</RelativeLayout>
Initializing RecyclerView:
recyclerView = findViewById(R.id.search_result_recyclerview);
recyclerView.scheduleLayoutAnimation();
recyclerView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("CheckRecyclerView","clicked");
}
});
searchResultRecyclerViewAdapter = new SearchResultRecyclerViewAdapter(bookModels,SearchActivity.this);
recyclerView.setAdapter(searchResultRecyclerViewAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(SearchActivity.this));
}
XML Layout of Activity:
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/drawerlayout"
android:layout_height="match_parent"
android:animateLayoutChanges="true"
android:layout_width="match_parent">
<RelativeLayout
android:layout_width="wrap_content"
android:gravity="center"
android:animateLayoutChanges="true"
android:layout_height="wrap_content"
android:orientation="vertical">
<!--
Views
-->
<androidx.recyclerview.widget.RecyclerView
android:layout_centerHorizontal="true"
android:layout_below="#id/appbar_cardview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/search_result_recyclerview"
android:layoutAnimation="#anim/search_result_recyclerview_anim"
android:visibility="gone"/> <!-- will become visible later-->
<!--
Views
-->
</RelativeLayout>
<com.google.android.material.navigation.NavigationView
app:itemTextColor="#color/white"
app:itemIconTint="#color/white"
android:background="#color/black"
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header"
app:menu="#menu/menu_main" />
</androidx.drawerlayout.widget.DrawerLayout>
when the item's view is clicked nothing happens. I've done the same exact thing before with no problem I don't know what I'm missing here.
EDIT:
as #anemomylos mentioned this might be a click issue. in this layout there is a lot of Views that will be Gone in order to RecyclerView shows up. RecyclerViews don't register any clicks themselves so I'm not sure if it's being blocked by another view or not, is there any way to know what is blocking the click? I don't have any android:clickable="true" and I made sure that all Views before RecyclerView are Gone and not Invisible
I'm trying to add a ripple effect for the entire row (like we see in listview) in my Recycler View when the row is clicked.
I have tried
android:background="?android:attr/selectableItemBackground"
android:clickable="true"
android:focusable="true"
But still, I couldn't get the desired behavior. Even I have tried
android:foreground="?android:attr/selectableItemBackground"
But still no improvement
My listrow.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:orientation="horizontal"
android:background="?android:attr/selectableItemBackground"
android:clickable="true"
android:focusable="true">
<RadioButton
android:id="#+id/radioButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/heading"
android:text="Title"
android:textSize="20dp"
android:paddingTop="5dp"
android:textStyle="bold"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:layout_toLeftOf="#+id/subHeading"
android:id="#+id/size"
android:text="Sub Title"
android:paddingTop="3dp"
android:paddingLeft="5dp"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
</LinearLayout>
And My layout with Recycler View
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content"
android:layout_width="match_parent">
<androidx.recyclerview.widget.RecyclerView
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clipToPadding="false"
android:paddingTop="#dimen/list_item_spacing_half"
android:paddingBottom="#dimen/list_item_spacing_half"
android:layout_alignParentTop="true"
tools:context=".ListFragment"
tools:listitem="#layout/listrow" />
<Button
android:id="#+id/Save"
android:layout_width="match_parent"
android:text="Save"
android:layout_below="#+id/list"
android:textAllCaps="false"
android:layout_height="wrap_content"/>
</RelativeLayout>
Here is my adapter source code
private class listAdapter extends RecyclerView.Adapter<ViewHolder> {
private final int mItemCount;
final ArrayList<String> mTitles;
final ArrayList<String> msTitles;
ArrayList<RadioButton> radioButtons=new ArrayList<>();
listAdapter(int itemCount, ArrayList<String> titles, ArrayList<String> sTitles) {
mItemCount = itemCount;
mtitles=titles;
msTitles=sTitles;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new ViewHolder(LayoutInflater.from(parent.getContext()), parent);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.sTitle.setTag(position);
holder.radioButton.setTag(position);
holder.title.setTag(position);
holder.title.setText(mTitles.get(position));
holder.sTitle.setText(msTitles.get(position));
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
ItemCheckChanged(v);
}
};
holder.radioButton.setOnClickListener(listener);
holder.sTitle.setOnClickListener(listener);
holder.title.setOnClickListener(listener);
if(radioButtons.size()==0){
holder.radioButton.setChecked(true);
selectedItem=0;
}
radioButtons.add(holder.radioButton);
}
#Override
public int getItemCount() {
return mItemCount;
}
void ItemCheckChanged(View v){
selectedItem=(int)v.getTag();
for(RadioButton radioButton:radioButtons){
radioButton.setChecked(false);
}
radioButtons.get(selectedItem).setChecked(true);
notifyDataSetChanged();
}
public int getSelectedIndex(){
return selectedItem;
}
}
NOTE: I'm using these all things in BottomSheetDialog may it be reason?
You should set background to views that have set a click listener.
If you want to set the listener to the whole row you need to call only:
holder.itemView.setOnclickListener() and remove rest of them.
BusinessForSaleActivity
public class BusinessForSaleActivity extends AppCompatActivity {
DatabaseReference databaseLinks;
ListView listViewBusinessForSale;
Button readMore;
ArrayList<BusinessForSale> list;
//CardView cardView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_business_for_sale);
listViewBusinessForSale = (ListView)findViewById(R.id.ListViewBusinessForSale);
list = new ArrayList<>();
databaseLinks = FirebaseDatabase.getInstance().getReference("BusinessList");
databaseLinks.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
list.clear();
try{
for(DataSnapshot businessSnapshot : dataSnapshot.getChildren()){
BusinessForSale b = businessSnapshot.getValue(BusinessForSale.class);
list.add(b);
}
}
catch (Exception ex){
Log.e("Error Descr:",ex.getMessage());
}
BusinessForSaleList adapter=new BusinessForSaleList(BusinessForSaleActivity.this,list);
listViewBusinessForSale.setAdapter(adapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(BusinessForSaleActivity.this,"Something is wrong",Toast.LENGTH_SHORT).show();
}
});
}
}
BusinessForSaleList================(Adapter class)============
public class BusinessForSaleList extends ArrayAdapter<BusinessForSale> {
private Activity context;
private List<BusinessForSale> businessForSaleList;
public BusinessForSaleList(Activity context,List<BusinessForSale> businessForSaleList){
//super(context,R.layout.list_layout,businessForSaleList);
super(context,R.layout.list,businessForSaleList);
this.context=context;
this.businessForSaleList=businessForSaleList;
}
#NonNull
#Override
public View getView(final int position, #Nullable View convertView, #NonNull ViewGroup parent) {
LayoutInflater inflater=context.getLayoutInflater();
View listViewItem=inflater.inflate(R.layout.list,null,true);
ImageView imgBuiness=(ImageView)listViewItem.findViewById(R.id.imgViewBusiness);
TextView txtTitle = (TextView)listViewItem.findViewById(R.id.txtViewTitle);
TextView txtType = (TextView)listViewItem.findViewById(R.id.txtViewType);
TextView txtDescr = (TextView)listViewItem.findViewById(R.id.txtViewDescr);
Button btnReadMore = (Button)convertView.findViewById(R.id.buttonReadMore);
BusinessForSale businessForSale = businessForSaleList.get(position);
Picasso.get().load(businessForSale.getImage().toString()).into(imgBuiness);
txtTitle.setText(businessForSale.getBusiness_Title());
txtType.setText(businessForSale.getBusiness_Type());
txtDescr.setText(businessForSale.getDescription());
return listViewItem;
}
}
BusinessForSaleActivity.xml==============================================
<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=".BusinessForSaleActivity">
<ListView
android:id="#+id/ListViewBusinessForSale"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:footerDividersEnabled="false"
/>
</RelativeLayout>
List.xml================================================================
[<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"
android:background="#e0e0e0">
<android.support.v7.widget.CardView
android:id="#+id/cardBusinessForSale"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="16dp"
app:cardCornerRadius="8dp"
app:cardElevation="4dp">
<LinearLayout
android:id="#+id/L1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView
android:id="#+id/imgViewBusiness"
android:layout_width="match_parent"
android:layout_height="160dp"
android:layout_margin="4dp"
android:scaleType="centerCrop"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="16dp">
<TextView
android:id="#+id/txtViewTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView"
android:layout_marginBottom="8dp"
android:textColor="#000"
android:textSize="18sp"/>
<TextView
android:id="#+id/txtViewType"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView"
android:textColor="#555" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="16dp"
android:orientation="vertical">
<TextView
android:id="#+id/txtViewDescr"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView"
android:maxLines="3"
android:textSize="14sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="16dp">
<Button
android:id="#+id/buttonReadMore"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:theme="#style/PrimaryFlatButton"
android:text="Read More" />
<Button
android:id="#+id/buttonAddToFvrt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:theme="#style/PrimaryFlatButton"
android:text="Add to Favorites" />
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
</RelativeLayout>][1]
I want to redirect to new Activity on "ReadMore" button click. I am fetching firebase data into a listview using list.xml layout.
When you're using a list and need to handle click on an item or an element contained by it, the common way is to set a listener in the getView() method or onBind() method, depending on the adepter you're using.
In this case, in your "getView()" method, after referenced your button you need to set a listener on it that retrieve the position of the item that contains it and open the relative activity (or the unique activity setting up the correct value). You can do it by retrieving the parent position of its parent, but it's sounds so complicated.
The best and common way is to assign to the button a tag that is the position assigned to its parent by the getView() method in this way:
#NonNull
#Override
public View getView(final int position, #Nullable View convertView, #NonNull ViewGroup parent) {
LayoutInflater inflater=context.getLayoutInflater();
View listViewItem=inflater.inflate(R.layout.list,null,true);
...
Button btnReadMore = (Button)convertView.findViewById(R.id.buttonReadMore);
btnReadMore.setTag(position + "");
}
After that, every button contains the position of the item in the list. Now, assign the listener to the button and retrieve the correct position:
btnReadMore.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View view,....){
Button btnReadMore = (Button) view; //This cast is unless, it's here only for more understanding
String positionString = btnReadMore.getTag();
int position = Integer.parseInt(positionString);
BusinessForSale correctItem = BusinessForSaleList.get(position);
//here start activity you need.
}});
Hope this help! :D
How can I delete the space when I hide a CardView? I doing an app with android and Firebase and I show the information from firebase in cardviews, but when the info isn't correct the cardview must disappear. The point is that the cardview disappear, but still uses a space in the layout, I've tried the answers in
setVisibility(GONE) view becomes invisible but still occupies space But it doesn't work for me.
#Override
protected void onStart() {
super.onStart();
firebaseAuth.addAuthStateListener(firebaseAuthListener);
final FirebaseRecyclerAdapter<CursosDB, MainActivity.CursosPViewHolder> firebaseRecyclerAdapter =
new FirebaseRecyclerAdapter<CursosDB, MainActivity.CursosPViewHolder>(
CursosDB.class,
R.layout.design_row_cursos,
MainActivity.CursosPViewHolder.class,
myRef)
{
#Override
protected void populateViewHolder(MainActivity.CursosPViewHolder viewHolder, final CursosDB Cmodel, int position)
{
String estado = Cmodel.getSTATUS().toString();
if (estado.equals("OK")){
viewHolder.setPhotoURL(getApplicationContext(), Cmodel.getURI());
viewHolder.setTitle(Cmodel.getTITLE());
viewHolder.setCiudad(Cmodel.getPLACE());
viewHolder.setLevel(Cmodel.getLEVEL());
viewHolder.setDur(Cmodel.getDURACION());
viewHolder.setPrice(Cmodel.getCOSTO());
}else{
RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) viewHolder.mView.getLayoutParams();
layoutParams.setMargins(0,0,0,0);
viewHolder.mView.setLayoutParams(layoutParams);
viewHolder.mView.setVisibility(View.INVISIBLE);
viewHolder.mView.setVisibility(View.GONE);
//viewHolder.mView.setVisibility(View.GONE);
//Toast.makeText(getApplicationContext(), "Ningún curso aprobado aún", Toast.LENGTH_SHORT).show();
}
viewHolder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Toast.makeText(getApplicationContext(), Cmodel.getUSERID(), Toast.LENGTH_LONG).show();
//Toast.makeText(getApplicationContext(), Cmodel.getTITLE(), Toast.LENGTH_SHORT).show();
//Toast.makeText(UsersList.this, user_key, Toast.LENGTH_LONG).show();
}
});
}
};
mCourses.setAdapter(firebaseRecyclerAdapter);
}
This is my layout:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/cardview_cursos"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="4dp"
android:onClick="positionAction"
android:padding="4dp"
android:paddingBottom="4dp"
android:paddingEnd="4dp"
android:paddingStart="4dp"
android:paddingTop="4dp"
app:cardElevation="4dp">
<LinearLayout android:id="#+id/layout_to_hide"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/Cimg"
android:layout_width="match_parent"
android:layout_height="165dp"
android:scaleType="center"
app:srcCompat="#drawable/knowit_logo" />
<TextView
android:id="#+id/Ctitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="#+id/Cimg"
android:layout_marginLeft="14dp"
android:layout_marginStart="14dp"
android:paddingTop="8dp"
android:text="Titulo"
android:textStyle="bold" />
<TextView
android:id="#+id/Clugar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/Ctitle"
android:layout_alignStart="#+id/Ctitle"
android:layout_below="#+id/Ctitle"
android:layout_marginTop="10dp"
android:text="Lugar" />
<TextView
android:id="#+id/textView29"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/Clugar"
android:layout_alignStart="#+id/Clugar"
android:layout_below="#+id/Clugar"
android:layout_marginTop="10dp"
android:text="$" />
<TextView
android:id="#+id/Cprice"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/textView29"
android:layout_marginBottom="4dp"
android:layout_toEndOf="#+id/textView29"
android:layout_toRightOf="#+id/textView29"
android:paddingLeft="5dp"
android:text="0.0" />
<TextView
android:id="#+id/Cdur"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/Clugar"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_marginEnd="126dp"
android:layout_marginRight="126dp"
android:text="Duración" />
<TextView
android:id="#+id/Cnivel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/Cprice"
android:layout_alignLeft="#+id/Cdur"
android:layout_alignStart="#+id/Cdur"
android:layout_marginBottom="0dp"
android:text="Nivel" />
</RelativeLayout>
</LinearLayout> </android.support.v7.widget.CardView>
This is the mView:
public static class CursosPViewHolder extends RecyclerView.ViewHolder {
View mView;
public CursosPViewHolder(final View itemView) {
super(itemView);
mView = itemView;
}
public void setTitle(String title){
TextView post_title = (TextView)mView.findViewById(R.id.Ctitle);
post_title.setText(title);
}
public void setCiudad (String ciudad){
TextView post_city = (TextView)mView.findViewById(R.id.Clugar);
post_city.setText(ciudad);
}
public void setPhotoURL(Context ctx, String pgotouserurl) {
ImageView post_image =(ImageView)mView.findViewById(R.id.Cimg);
Picasso.with(ctx).load(pgotouserurl).into(post_image);
} }
I hope you can help me.
First the XML code you've posted ils wrong closed,(must finish with a CardView tag)
On addition be sure you're pointing the CardView layout with mView field ans Only use GONE or INVISIBLE,
INVISIBLE change your Panel ( Root view ) structure but GONE don't
I'm trying to create a Chat App. It is working really good. But now I'd like to gravity the messages. I don't know how I can set the gravity of the sent messages to the right side. viewHolder.mView.setForegroundGravity(); doesn't work.
public void populateViewHolder(final BlogViewHolder viewHolder, final Blog model, final int position) {
DatabaseReference getname = FirebaseDatabase.getInstance().getReference().child("Users").child(userID).child("Username");
getname.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//Grün und weiß setzen
String myname = dataSnapshot.getValue(String.class);
if(myname.equals(model.getUsername())){
LinearLayout linear = (LinearLayout)findViewById(R.id.singleMessageContainer);
linear.setGravity(Gravity.RIGHT);
viewHolder.setNachricht(model.getNachricht());
}else{
viewHolder.setNachricht(model.getNachricht());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
public static class BlogViewHolder extends RecyclerView.ViewHolder{
View mView;
public BlogViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setNachricht(String Nachricht){
TextView post_Nachricht = (TextView)mView.findViewById(R.id.textViewMessage);
post_Nachricht.setText(Nachricht);
}
public void setUsername(String Username){
TextView post_Nachricht = (TextView)mView.findViewById(R.id.kommentareimg);
post_Nachricht.setText(Html.fromHtml("<b>" + Username + ":</b>"));
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/singleMessageContainer"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="6dp">
<LinearLayout
android:id="#+id/warpper"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/textViewMessage"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_marginBottom="2dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="2dp"
android:text="Message"
android:textSize="14sp"
tools:ignore="HardcodedText" />
</LinearLayout>
</LinearLayout>
In your case you might consider having two TextView in your list item layout. Make the layout such that one layout is aligned to the right and the other is aligned to the left. Now you just have to set the visibility of the left or right layout to GONE or VISIBLE.
So you need to have some other functions in your ViewHolder class.
public static class BlogViewHolder extends RecyclerView.ViewHolder{
View mView;
public BlogViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setNachrichtRight(String Nachricht) {
TextView post_Nachricht_Right = (TextView)mView.findViewById(R.id.textViewMessageRight);
TextView post_Nachricht_Left = (TextView)mView.findViewById(R.id.textViewMessageLeft);
post_NachrichtRight.setText(Nachricht);
// Now set the visibility
post_Nachricht_Right.setVisibility(View.VISIBLE);
post_Nachricht_Left.setVisibility(View.GONE);
}
public void setNachrichtLeft(String Nachricht) {
TextView post_NachrichtLeft = (TextView)mView.findViewById(R.id.textViewMessageLeft);
TextView post_NachrichtRight = (TextView)mView.findViewById(R.id.textViewMessageRight);
post_NachrichtLeft.setText(Nachricht);
// Now set the visibility
post_Nachricht_Right.setVisibility(View.VISIBLE);
post_Nachricht_Left.setVisibility(View.GONE);
}
public void setUsername(String Username){
TextView post_Nachricht = (TextView)mView.findViewById(R.id.kommentareimg);
post_Nachricht.setText(Html.fromHtml("<b>" + Username + ":</b>"));
}
}
So inside the onDataChange function you may consider doing something like this.
if(myname.equals(model.getUsername())){
viewHolder.setNachrichtRight(model.getNachricht());
} else {
viewHolder.setNachrichtLeft(model.getNachricht());
}
Finally, your layout may look something like this
<?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:id="#+id/singleMessageContainer"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="6dp">
<TextView
android:id="#+id/textViewMessageRight"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="2dp"
android:alignParentRight="true"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="2dp"
android:text="Message"
android:textSize="14sp"
tools:ignore="HardcodedText" />
<TextView
android:id="#+id/textViewMessageLeft"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:alignParentLeft="true"
android:layout_marginBottom="2dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="2dp"
android:text="Message"
android:textSize="14sp"
tools:ignore="HardcodedText" />
</RelativeLayout>