I want to use view holder pattern in my firebase list adapter. The firebase adapter looks a bit different than the ones with converter view because here in populateView method, the view parameter can't be null and always have a value, so I'm looking for the best way to implement the view holder pattern.
Here is my adapter class:
public class NewsAdapter extends FirebaseListAdapter<News> {
public NewsAdapter(Activity activity, Class<News> modelClass, int modelLayout, Query ref) {
super(activity, modelClass, modelLayout, ref);
}
#Override
protected void populateView(View view, final News news, int i) {
final Context context = view.getContext();
final String title = news.getTitle();
final String photoUrl = news.getPhotoUrl();
// Create views and assign values
ImageView ivPhoto = (ImageView) view.findViewById(R.id.iv_news_photo);
if (photoUrl != null)
// Load the image using Glide
Glide.with(context)
.load(photoUrl)
.into(ivPhoto);
TextView tvTitle = (TextView) view.findViewById(R.id.tv_news_title);
tvTitle.setText(title)
}
}
Here is View Holder
public class TaskViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView title,desc,points,remaining;
public ImageView image;
public ItemClickListener clickListener;
public TaskViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.task_title);
desc = (TextView) itemView.findViewById(R.id.task_description);
points = (TextView) itemView.findViewById(R.id.task_point);
remaining = (TextView) itemView.findViewById(R.id.task_remaining_entries);
image = (ImageView) itemView.findViewById(R.id.task_image);
itemView.setOnClickListener(this);
}
public void setClickListener(ItemClickListener clickListener) {
this.clickListener = clickListener;
}
#Override
public void onClick(View view) {
Toast.makeText(view.getContext(), "clicked on task item", Toast.LENGTH_SHORT).show();
clickListener.onClick(view,getAdapterPosition(),false);
}
}
and here is what i'm doing to load data in RecyclerView
public void loadData(){
database = FirebaseDatabase.getInstance();
tasks = database.getReference("Tasks");
adapter = new FirebaseRecyclerAdapter<TaskPOJO, TaskViewHolder>(TaskPOJO.class, R.layout.task_item, TaskViewHolder.class, tasks) {
#Override
protected void populateViewHolder(TaskViewHolder viewHolder, final TaskPOJO model, int position) {
Log.wtf("TEstScript1", "populateViewHolder: "+model.getTitle() );
viewHolder.title.setText(model.getTitle());
viewHolder.desc.setText(model.getDescripttion()+"\n");
viewHolder.remaining.setText(model.getRemaining()+"/"+model.getPoint());
viewHolder.points.setText("Points "+model.getRemaining());
Glide.with(viewHolder.title.getContext())
.load(model.getImage())
.into(viewHolder.image);
viewHolder.setClickListener(new ItemClickListener() {
#Override
public void onClick(View view, int position, boolean isLongClick) {
Toast.makeText(getActivity(), "" + model.getTitle(), Toast.LENGTH_SHORT).show();
Intent TaskPOJODetail = new Intent(getActivity(), Main.class);
TaskPOJODetail.putExtra("value","detail");
TaskPOJODetail.putExtra("taskId",adapter.getRef(position).getKey());
startActivity(TaskPOJODetail);
}
});
}
};
recyclerViewTasks.setAdapter(adapter);
}
here is my task_item.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:elevation="8dp"
android:clipChildren="true"
android:clipToPadding="true"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="130dp"
android:orientation="horizontal"
>
<ImageView
android:layout_width="110dp"
android:layout_height="130dp"
android:id="#+id/task_image"
android:src="#drawable/test_tast"
android:scaleType="centerCrop"
/>
<View
android:layout_width="4dp"
android:layout_height="match_parent"
android:background="#color/colorAccent"
android:layout_alignParentRight="true"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/task_image"
android:orientation="vertical"
android:layout_marginTop="8dp"
android:layout_marginLeft="8dp"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Title of Task"
android:textSize="18sp"
android:textColor="#color/colorAccent"
android:id="#+id/task_title"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="30/300"
android:textSize="18sp"
android:layout_marginRight="16dp"
android:textColor="#color/colorAccent"
android:layout_alignParentRight="true"
android:id="#+id/task_remaining_entries"
/>
</RelativeLayout>
<me.biubiubiu.justifytext.library.JustifyTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Loren Ipsum is Simply dummy text of the printing and type settin industry. Developers and designers frequently use this\n "
android:layout_marginRight="16dp"
android:maxLines="3"
android:id="#+id/task_description"
android:lineSpacingMultiplier="1.1"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Point 2345345"
android:textColor="#android:color/white"
android:background="#color/colorAccent"
android:layout_gravity="right"
android:paddingRight="16dp"
android:paddingTop="8dp"
android:paddingBottom="8dp"
android:paddingLeft="16dp"
android:layout_marginTop="8dp"
android:id="#+id/task_point"
/>
</LinearLayout>
</RelativeLayout>
</android.support.v7.widget.CardView>
hope this will help you.
You can find below example as a reference,
public class RecipeHolder extends RecyclerView.ViewHolder{
private static final String TAG = RecipeHolder.class.getSimpleName();
public TextView recipeName;
public ImageView recipeImage;
public RecipeHolder(View itemView) {
super(itemView);
recipeName = (TextView)itemView.findViewById(R.id.recipe_name);
recipeImage = (ImageView)itemView.findViewById(R.id.recipe_image);
}
}
And create your custom adapter
public class RecipeAdapter extends FirebaseRecyclerAdapter<RecipeObject, RecipeHolder>{
private static final String TAG = RecipeAdapter.class.getSimpleName();
private Context context;
public RecipeAdapter(Class<RecipeObject> modelClass, int modelLayout, Class<RecipeHolder> viewHolderClass, DatabaseReference ref, Context context) {
super(modelClass, modelLayout, viewHolderClass, ref);
this.context = context;
}
#Override
protected void populateViewHolder(RecipeHolder viewHolder, RecipeObject model, int position) {
viewHolder.recipeName.setText(model.getRecipename());
Glide.with(context).load(model.getRecipeImageUrl()).into(viewHolder.recipeImage);
}
}
For more reference you can refer FirebaseRecyclerView Adapter
Related
I have been trying to fill my Recycler view from Firebase Realtime Database, but this is the result:
Emtpty Cards in Recycler View
I am pretty sure that I have followed all the steps. What is surprising is that even though the contents aren't loading, the number of empty cards that have loaded are correct.
This is my Database:
Picture of Firebase Database
This is my Layout file with Card View:
<com.google.android.material.card.MaterialCardView
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="wrap_content"
android:padding="10dp"
android:layout_marginTop="10dp"
android:layout_marginStart="15dp"
android:layout_marginEnd="15dp"
app:cardElevation="15dp"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="10dp">
<ImageView
android:id="#+id/food_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:srcCompat="#tools:sample/avatars" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="10dp">
<TextView
android:id="#+id/food_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ITEM NAME"
android:textSize="18sp" />
<LinearLayout
android:orientation="horizontal"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:padding="10dp">
<TextView
android:id="#+id/food_price"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="PRICE:"/>
</LinearLayout>
<com.google.android.material.button.MaterialButton
android:id="#+id/addtocart_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
style="?attr/borderlessButtonStyle"
android:text="ADD TO CART"/>
</LinearLayout>
</LinearLayout>
</com.google.android.material.card.MaterialCardView>
This is my Model Class:
package com.example.dubstep.Model;
public class FoodItem {
String base_price;
String name;
public FoodItem(){
}
public FoodItem(String price, String name) {
this.base_price = price;
this.name = name;
}
public String getBase_price() {
return base_price;
}
public void setBase_price(String base_price) {
this.base_price = base_price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Here is my ViewHolder Class:
public class FoodItemViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView mFoodItemName;
public ImageView mFoodImage;
public TextView mFoodItemPrice;
public MaterialButton mAddToCart;
public ItemClickListener listener;
public FoodItemViewHolder(#NonNull View itemView) {
super(itemView);
mFoodItemName = (TextView) itemView.findViewById(R.id.food_name);
mFoodItemPrice = (TextView) itemView.findViewById(R.id.food_price);
mFoodImage = (ImageView) itemView.findViewById(R.id.food_image);
mAddToCart = (MaterialButton) itemView.findViewById(R.id.addtocart_btn);
}
public void setItemClickListener(ItemClickListener listener){
this.listener = listener;
}
#Override
public void onClick(View v) {
listener.onClick(v,getAdapterPosition(),false);
}
}
I have used Firebase Recycler Adapter in my Main Activity OnStart:
FirebaseRecyclerOptions<FoodItem> options = new FirebaseRecyclerOptions.Builder<FoodItem>().setQuery(foodref,FoodItem.class).build();
FirebaseRecyclerAdapter<FoodItem, FoodItemViewHolder> adapter =
new FirebaseRecyclerAdapter<FoodItem, FoodItemViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull FoodItemViewHolder holder, int position, #NonNull FoodItem model) {
holder.mFoodItemName.setText(model.getName());
holder.mFoodItemPrice.setText("Price: "+model.getBase_price());
}
#NonNull
#Override
public FoodItemViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.food_item_layout,parent,false);
FoodItemViewHolder holder = new FoodItemViewHolder(view);
return holder;
}
};
recyclerView.setAdapter(adapter);
adapter.startListening();
And in my OnCreate I have initialized my Recycler View and Layout Manager:
foodref = FirebaseDatabase.getInstance().getReference().child("food_menu");
recyclerView = findViewById(R.id.main_recyclerview);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(MainActivity.this);
recyclerView.setLayoutManager(layoutManager);
Can Someone help me and tell me where I might be going wrong?
Thank you!
My RecyclerView's item layout has a ViewPager on top and some views below it. ViewPager works fine, swipes good. But the recycler item click is not working on clicking the ViewPager (I've set click on the entire item). But if I click the content below the ViewPager, Click works.
here's the RecyclerView's list item
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content" xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:card_view="http://schemas.android.com/tools"
android:orientation="horizontal"
xmlns:attrs="http://schemas.android.com/apk/res-auto">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
card_view:cardBackgroundColor="#android:color/white"
card_view:cardCornerRadius="8dp"
card_view:cardElevation="6dp"
card_view:cardUseCompatPadding="true"
android:layout_marginTop="8dp"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:layout_marginBottom="8dp">
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="0dp" android:layout_height="0dp"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintDimensionRatio="H,4:2"/>
<com.rd.PageIndicatorView
android:id="#+id/pageIndicatorView"
android:layout_width="wrap_content"
android:layout_height="20dp"
app:piv_animationType="scale"
app:piv_dynamicCount="true"
app:piv_interactiveAnimation="true"
app:piv_selectedColor="#color/whiteSmoke"
app:piv_unselectedColor="#color/white25Transparent"
app:piv_viewPager="#id/viewPager"
attrs:piv_padding="2dp"
attrs:piv_radius="4dp"
app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintBottom_toBottomOf="#id/viewpager" android:layout_marginBottom="0dp"/>
<com.codeairs.wattamatte.customcontrols.textview.MPRegularTextView
android:id="#+id/name"
android:layout_width="0dp" android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="#id/viewpager" android:layout_marginTop="6dp"
app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent"
android:layout_marginStart="12dp" android:layout_marginLeft="12dp"
android:layout_marginEnd="12dp" android:layout_marginRight="12dp"
android:text="Cosy Duplex - 42m2" android:textColor="#color/stPatricksBlue"/>
<com.codeairs.wattamatte.customcontrols.textview.MPMediumTextView
android:id="#+id/tv1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="#style/RoomDimensTextView"
app:layout_constraintTop_toBottomOf="#id/name" android:layout_marginTop="6dp"
app:layout_constraintStart_toStartOf="#id/name"
android:text="3p"/>
<com.codeairs.wattamatte.customcontrols.textview.MPMediumTextView
android:id="#+id/tv2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="#style/RoomDimensTextView"
app:layout_constraintTop_toBottomOf="#id/name" android:layout_marginTop="6dp"
app:layout_constraintStart_toEndOf="#id/tv1"
android:layout_marginStart="12dp" android:layout_marginLeft="12dp"
android:text="2ch"/>
<com.codeairs.wattamatte.customcontrols.textview.MPMediumTextView
android:id="#+id/tv3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="#style/RoomDimensTextView"
app:layout_constraintTop_toBottomOf="#id/name" android:layout_marginTop="6dp"
app:layout_constraintStart_toEndOf="#id/tv2"
android:layout_marginStart="12dp" android:layout_marginLeft="12dp"
android:text="4m"/>
<com.codeairs.wattamatte.customcontrols.textview.MPRegularTextView
android:id="#+id/location"
android:layout_width="0dp" android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="#id/tv1" android:layout_marginTop="6dp"
app:layout_constraintStart_toStartOf="#id/tv1" app:layout_constraintEnd_toEndOf="parent"
android:text="Villeurbanne" android:textColor="#color/darkSlateBlue"
app:layout_constraintBottom_toBottomOf="parent" android:layout_marginBottom="4dp"/>
<com.codeairs.wattamatte.customcontrols.textview.MPBoldTextView
android:id="#+id/price"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintEnd_toEndOf="parent" android:layout_marginEnd="12dp"
android:layout_marginRight="12dp"
app:layout_constraintBottom_toBottomOf="parent" android:layout_marginBottom="12dp"
android:text="450€ C.C" android:textColor="#color/stPatricksBlue" android:textSize="17sp"/>
<View
android:id="#+id/toggleBG"
android:layout_width="36dp" android:layout_height="36dp"
android:background="#drawable/solid_white_circle"
app:layout_constraintEnd_toEndOf="parent"
android:layout_marginEnd="8dp" android:layout_marginRight="8dp"
app:layout_constraintTop_toBottomOf="#id/viewpager"
app:layout_constraintBottom_toBottomOf="#id/viewpager"/>
<ToggleButton
android:id="#+id/favoritesToggleButton"
android:layout_width="24dp"
android:layout_height="24dp"
android:background="#drawable/bg_fav_toggle"
android:textOn=""
android:textOff=""
app:layout_constraintTop_toTopOf="#id/toggleBG"
app:layout_constraintBottom_toBottomOf="#id/toggleBG"
app:layout_constraintStart_toStartOf="#id/toggleBG"
app:layout_constraintEnd_toEndOf="#id/toggleBG"/>
</android.support.constraint.ConstraintLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
RecylerView Adapter
public class RoomsListRecyclerViewAdapter extends RecyclerView.Adapter<RoomsListRecyclerViewAdapter.ViewHolder> {
private final List<Room> mValues;
private final List<String> favRoomsIds;
private final OnListFragmentInteractionListener mListener;
private final Context mContext;
public RoomsListRecyclerViewAdapter(List<Room> items, List<String> favRoomsIds,
OnListFragmentInteractionListener listener, Context mContext) {
mValues = items;
mListener = listener;
this.favRoomsIds = favRoomsIds;
this.mContext = mContext;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.fragment_rooms_list_item, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, int position) {
holder.mItem = mValues.get(position);
holder.imgPager.setAdapter(new ImageAdapter(mContext, holder.mItem.property.pictures));
holder.pageIndicatorView.setCount(holder.mItem.property.pictures.size());
holder.pageIndicatorView.setSelection(0);
holder.imgPager.addOnPageChangeListener(getPageChangeListener(holder));
holder.name.setText(holder.mItem.property.name);
holder.location.setText(holder.mItem.property.address.city);
holder.price.setText(MessageFormat.format("{0} € C.C", holder.mItem.property.price));
holder.tv1.setText(MessageFormat.format("{0}p", holder.mItem.property.personCount));
holder.tv2.setText(MessageFormat.format("{0}ch", holder.mItem.property.pieces));
holder.tv3.setText(MessageFormat.format("{0}m²", holder.mItem.property.surface));
holder.favToggle.setChecked(favRoomsIds.contains(holder.mItem.property.id));
holder.favToggle.setOnCheckedChangeListener((buttonView, isChecked) ->
toggleFavorite(holder.mItem.property.id, isChecked));
holder.mView.setOnClickListener(v -> {
if (null != mListener) {
mListener.onListFragmentInteraction(holder.mItem, favRoomsIds.contains(holder.mItem.property.id));
}
});
}
#Override
public int getItemCount() {
return mValues.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
final View mView;
Room mItem;
ViewPager imgPager;
TextView name, location, price, tv1, tv2, tv3;
ToggleButton favToggle;
PageIndicatorView pageIndicatorView;
ViewHolder(View view) {
super(view);
mView = view;
imgPager = view.findViewById(R.id.viewpager);
name = view.findViewById(R.id.name);
location = view.findViewById(R.id.location);
price = view.findViewById(R.id.price);
tv1 = view.findViewById(R.id.tv1);
tv2 = view.findViewById(R.id.tv2);
tv3 = view.findViewById(R.id.tv3);
favToggle = view.findViewById(R.id.favoritesToggleButton);
pageIndicatorView = view.findViewById(R.id.pageIndicatorView);
}
#Override
public String toString() {
return super.toString() + " '" + "'";
}
}
private void toggleFavorite(String propertyId, boolean fav) {
if (fav)
favRoomsIds.add(propertyId);
else
favRoomsIds.remove(propertyId);
JsonObjectRequest request = NetworkUtils.toggleRoomFavoritesRequest(
mContext, propertyId, fav, this::handleResponse, this::handleError);
VolleySingleton.getInstance(mContext).addToRequestQueue(request);
}
private void handleResponse(JSONObject response) {
Log.d("RoomFav.Response", response.toString());
}
private void handleError(VolleyError error) {
}
public void clear() {
mValues.clear();
notifyDataSetChanged();
}
public void addItems(List<Room> rooms) {
mValues.addAll(rooms);
notifyDataSetChanged();
}
private ViewPager.OnPageChangeListener getPageChangeListener(ViewHolder holder) {
return new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
holder.pageIndicatorView.setSelected(position);
}
#Override
public void onPageScrollStateChanged(int state) {
}
};
}
}
pager adapter
public class ImageAdapter extends PagerAdapter {
private Context mContext;
private List<String> mItems;
public ImageAdapter(Context context, List<String> items) {
mContext = context;
mItems = items;
}
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup collection, int position) {
LayoutInflater inflater = LayoutInflater.from(mContext);
ImageView img = (ImageView) inflater.inflate(R.layout.layout_image, collection, false);
String url = mItems.get(position);
if (!TextUtils.isEmpty(url))
Picasso.get().load(ApiPaths.IMG_PATH_PREFIX + url).into(img);
collection.addView(img);
return img;
}
#Override
public void destroyItem(#NonNull ViewGroup collection, int position, #NonNull Object view) {
collection.removeView((View) view);
}
#Override
public int getCount() {
return mItems.size();
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object object) {
return view == object;
}
}
pager item
<ImageView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/img"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:scaleType="fitXY"
android:clickable="false"/>
I have an android app where I have used RecyclerView that shows a list of contacts. Now what I want is that when selecting the contacts, call the indicated number.
For now all it do is show the contacts, but when i click on it it calls, it does not do any action. I do not know how to get it to mark
I tried with onClick() and with button item.But Unsuccessful
My code:
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder> {
private static final String TAG = "RecyclerViewAdapter";
Context mContext;
List<Contact> mData;
Dialog myDialog;
Button button;
public RecyclerViewAdapter(Context mContext, List<Contact> mData) {
this.mContext = mContext;
this.mData = mData;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v ;
v = LayoutInflater.from(mContext).inflate(R.layout.single_item_contact,parent,false);
final MyViewHolder vHolder = new MyViewHolder(v);
// Dialog ini
myDialog = new Dialog(mContext);
myDialog.setContentView(R.layout.dialog_contact);
myDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
vHolder.item_contact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Toast.makeText(mContext,"Text Click item : "+String.valueOf(vHolder.getAdapterPosition()),Toast.LENGTH_SHORT).show();
TextView dialog_name_tv = (TextView) myDialog.findViewById(R.id.dialog_name_id);
TextView dialog_phone_tv = (TextView) myDialog.findViewById(R.id.dialog_phone_id);
ImageView dialog_contact_img = (ImageView)myDialog.findViewById(R.id.dialog_img);
dialog_name_tv.setText(mData.get(vHolder.getAdapterPosition()).getName());
dialog_phone_tv.setText(mData.get(vHolder.getAdapterPosition()).getPhone());
dialog_contact_img.setImageResource(mData.get(vHolder.getAdapterPosition()).getPhoto());
myDialog.show();
}
});
return vHolder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, final int position) {
holder.tv_name.setText(mData.get(position).getName());
holder.tv_phone.setText(mData.get(position).getPhone());
holder.img.setImageResource(mData.get(position).getPhoto());
}
#Override
public int getItemCount() {
return mData.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
private LinearLayout item_contact;
private TextView tv_name;
private TextView tv_phone;
private ImageView img;
public MyViewHolder(View itemView) {
super(itemView);
item_contact = (LinearLayout) itemView.findViewById(R.id.contact_item_id);
tv_name = (TextView) itemView.findViewById(R.id.name_contact);
tv_phone = (TextView) itemView.findViewById(R.id.phone_contact);
img = (ImageView) itemView.findViewById(R.id.img_contact);
}
}
}
Aquí muestro mi XML de como tengo.
help please
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="350dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginTop="15dp"
android:background="#232323"
android:gravity="center_horizontal"
android:orientation="vertical">
<TextView
android:id="#+id/dialog_name_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="90dp"
android:text="Contact Name"
android:textColor="#android:color/white"
android:textSize="30sp"
android:textStyle="bold" />
<TextView
android:id="#+id/dialog_phone_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:layout_marginTop="5dp"
android:text="Phone Number"
android:textColor="#android:color/white"
android:textSize="23sp" />
<Button
android:id="#+id/dialog_btn_call"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="start"
android:layout_marginTop="10dp"
android:background="#android:color/white"
android:drawableLeft="#drawable/dialog_call_black"
android:drawablePadding="20dp"
android:padding="20dp"
android:text="Llamar"
android:textAlignment="textStart"
android:textSize="25dp" />
<Button
android:id="#+id/dialog_btn_msg"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="start"
android:background="#android:color/white"
android:drawableLeft="#drawable/dialog_message_black"
android:drawablePadding="20dp"
android:padding="20dp"
android:text="Mensaje"
android:textAlignment="textStart"
android:textSize="25dp" />
</LinearLayout>
<ImageView
android:id="#+id/dialog_img"
android:layout_width="120dp"
android:layout_height="120dp"
android:src="#drawable/ic_contacts"
android:padding="10dp"
android:layout_centerHorizontal="true"
android:layout_alignParentTop="true"
/>
</RelativeLayout>
You need to put setOnClickListener() into OnBindViewHolder().So far what i understand is you have Recycler View in which on item click you want to open a dialog box dialog_contact and this dialog box contains Contact information. After opening this dialog you want to call that person by clicking call button present in dialog.
#Override
public void onBindViewHolder(MyViewHolder holder, final int position) {
holder.tv_name.setText(mData.get(position).getName());
holder.tv_phone.setText(mData.get(position).getPhone());
holder.img.setImageResource(mData.get(position).getPhoto());
holder.item_contact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myDialog = new Dialog(mContext);
myDialog.setContentView(R.layout.dialog_contact);
myDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
myDialog.show();
TextView dialog_name_tv = (TextView)myDialog.findViewById(R.id.dialog_name_id);
Button dialog_btn_call= (Button )myDialog.findViewById(R.id.dialog_btn_call);
TextView dialog_phone_tv = (TextView) myDialog.findViewById(R.id.dialog_phone_id);
ImageView dialog_contact_img = (ImageView)myDialog.findViewById(R.id.dialog_img);
dialog_name_tv.setText(mData.get(vHolder.getAdapterPosition()).getName());
dialog_phone_tv.setText(mData.get(vHolder.getAdapterPosition()).getPhone());
dialog_contact_img.setImageResource(mData.get(vHolder.getAdapterPosition()).getPhoto());
dialog_btn_call.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Do your code here
myDialog.dismiss();
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:" +mData.get(holder.getAdapterPosition()).getPhone()));
mContext.startActivity(intent);
}
});
}
});
}
Edit:-
I'm trying to adapt a recyclerview to display a list of objects. But actually I have some kind of wierd bug. My object have ID and Name data to display, but in the list, at first, I only can see the Id, and when I scroll down, only the rows going completely out of the screen are completely displayed...
This is my ListPresentActivity.
public class ListPresentActivity extends AppCompatActivity implements ViewInterface {
private static final String EXTRA_PRESENT_ID = "EXTRA_PRESENT_ID";
private static final String EXTRA_PRESENT_NAME = "EXTRA_PRESENT_NAME";
private List<PresentItem> listOfPresent;
private LayoutInflater layoutInflater;
private RecyclerView recyclerView;
private CustomAdapter adapter;
private PresentController presentController;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_present);
recyclerView = (RecyclerView) findViewById(R.id.rec_list_activity);
recyclerView.setHasFixedSize(true);
layoutInflater = getLayoutInflater();
presentController = new PresentController(this, new FakePresentModel());
}
#Override
public void startDetailActivity(int id, String name, String info, String target, String advice, String price) {
//public void startDetailActivity(int id) {
Intent i = new Intent(this,PresentDetailActivity.class);
i.putExtra(EXTRA_PRESENT_ID, id);
i.putExtra(EXTRA_PRESENT_NAME, name);
startActivity(i);
}
#Override
public void setUpAdapterAndView(List<PresentItem> listOfPresent) {
this.listOfPresent = listOfPresent;
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter = new CustomAdapter();
recyclerView.setAdapter(adapter);
}
private class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.CustomViewHolder>{
#Override
public CustomAdapter.CustomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = layoutInflater.inflate(R.layout.item_present, parent, false);
return new CustomViewHolder(v);
}
#Override
public void onBindViewHolder(CustomAdapter.CustomViewHolder holder, int position) {
PresentItem currentPresent = listOfPresent.get(position);
holder.id.setText(
Integer.toString(currentPresent.getId())
);
holder.name.setText(
currentPresent.getName()
);
}
#Override
public int getItemCount() {
return listOfPresent.size();
}
class CustomViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
private TextView id;
private TextView name;
private ViewGroup container;
public CustomViewHolder(View itemView){
super(itemView);
this.id = (TextView) itemView.findViewById(R.id.texv_item_id);
this.name = (TextView) itemView.findViewById(R.id.texv_item_name);
this.container = (ViewGroup) itemView.findViewById(R.id.root_list_present);
this.container.setOnClickListener(this);
}
#Override
public void onClick(View v) {
PresentItem presentItem = listOfPresent.get(
this.getAdapterPosition()
);
presentController.onListItemClick(presentItem);
}
}
}
}
The layout item_present.xml
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="88dp"
android:id="#+id/root_list_present"
xmlns:tools="http://schemas.android.com/tools">
<TextView
android:id="#+id/texv_item_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:textSize="48sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:text="#id" />
<TextView
android:id="#+id/texv_item_name"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="84dp"
android:layout_marginTop="8dp"
android:ellipsize="end"
android:maxLines="1"
android:textSize="20sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:text="collier" />
</android.support.constraint.ConstraintLayout>
And my list layout
<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="net.lubbee.bruh.view.ListPresentActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/rec_list_activity"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</android.support.constraint.ConstraintLayout>
I have search for a long time now, and the only concording result I have fount seems to be fixed with the recyclerView.setHasFixedSize(true); which is not my case...
Thanks for your time!
PS : If there is some code parts needed missing, just say the word! :]
Just after the first loading.
After one scroll to the bottom and back to the top of the screen
<LinearLayout android:layout_width="match_parent"
android:layout_height="88dp"
android:weightSum="1"
xmlns:android="http://schemas.android.com/apk/res/android">
<TextView
android:layout_gravity="center_vertical"
android:layout_weight="0.2"
android:layout_width="0dp"
android:layout_height="wrap_content" />
<TextView
android:layout_gravity="center_vertical"
android:layout_weight="0.8"
android:layout_width="0dp"
android:layout_height="wrap_content" />
</LinearLayout>
Try this simple LinearLayout it should work
You can also add other properties, but for now try it out
I want to create a list of items that have a background image and a TextView. Although it creates the RecyclerView normally and sets the text, the background image doesn't set.
This is my Adapter Class
public class Casino_Adapter extends RecyclerView.Adapter<Casino_Adapter.ViewHolder> {
private Data[] mDataset;
private ClickListener clickListener;
public Context context;
// Provide a suitable constructor (depends on the kind of dataset)
public Casino_Adapter(Data[] myDataset) {
this.mDataset = myDataset;
this.context = context;
}
#Override
public Casino_Adapter.ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
// create a new view
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.casino_card_row, parent, false);
// set the view's size, margins, paddings and layout parameters
ViewHolder vh = new ViewHolder(v);
return vh;
}
public static class ViewHolder extends RecyclerView.ViewHolder {
private final Context context = null;
// each data item is just a string in this case
public TextView mTextView;
public ImageView mImageView;
public CardView cardView;
//Typeface tf;
public ViewHolder(View v) {
super(v);
mTextView = (TextView) v.findViewById(R.id.text);
mImageView = (ImageView) v.findViewById(R.id.image);
cardView = (CardView) v.findViewById(R.id.card_view);
//cardView.setPreventCornerOverlap(false);
}
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
// - get element from your dataset at this position
// - replace the contents of the view with that element
holder.mTextView.setText(mDataset[position].getText());
holder.mImageView.setImageResource(mDataset[position].getImage());
}
public void setClickListener(ClickListener clickListener) {
this.clickListener = clickListener;
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
return mDataset.length;
}
public interface ClickListener {
public void itemClicked(View view, int pos);
}
}
I have a Fragment Class where I want the RecyclerView to be.
public class CasinoFragment extends Fragment {
protected RecyclerView recyclerView;
protected RecyclerView.Adapter mAdapter;
protected RecyclerView.LayoutManager mLayoutManager;
public CasinoFragment() {
// Required empty public constructor
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initial();
}
private void initial() {
final Data datas[] =
{
new Data("This is an item", R.drawable.ic_home_white_36dp),
new Data("This is an item 2", R.drawable.car),
new Data("asdasd`sdads", R.drawable.car),
new Data("This is an item 3", R.drawable.car)
};
mAdapter = new Casino_Adapter(datas);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_casino, container, false);
recyclerView = (RecyclerView) view.findViewById(R.id.my_recycler_view);
mLayoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setAdapter(mAdapter);
return view;
}
}
And these are the Setters that I use.
public class Data {
int image;
String text;
public Data(String title, int backimage)
{
this.text = title;
this.image = backimage;
}
public String getText()
{
return text;
}
public int getImage()
{
return image;
}
public void setText()
{
this.text=text;
}
public void setImageID()
{
this.image = image;
}
}
Casino Row 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="match_parent"
android:layout_height="wrap_content"
card_view:cardCornerRadius="8dp"
android:layout_margin="5dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#111111"
>
<ImageView
android:layout_width="match_parent"
android:layout_height="200dp"
android:id="#+id/image"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:adjustViewBounds="true"
android:scaleType="centerCrop"
android:background="#drawable/image_round"
android:src="#drawable/car" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignBottom="#+id/image"
android:id="#+id/rel_color"
android:background="#4c4c4c">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Μπύρα"
android:textColor="#fcfcfc"
android:textSize="30sp"
android:shadowColor="#000000"
android:shadowDx="3"
android:shadowDy="3"
android:shadowRadius="5"
android:id="#+id/text"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
</RelativeLayout>
</android.support.v7.widget.CardView>
The result I get is the following.
The reason why you aren't seeing your image, is because it isn't actually visible.
Your rel_color layout has the same size attributes as your ImageView.
If you want to display a layout above the ImageView, you just need to remove the background of it, otherwise the ImageView will be hidden.
Just Like that. but remember your images dimensions must be low. in my case i used 200x200
<?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/rl_menu_item"
android:layout_width="match_parent"
android:layout_height="150dp"
android:layout_margin="5dp"
android:background="#android:color/transparent"
card_view:cardCornerRadius="4dp"
card_view:cardUseCompatPadding="true">
<RelativeLayout
android:id="#+id/img_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/bg_blrr">
<ImageView
android:id="#+id/iv_icon"
android:layout_width="90dp"
android:layout_height="90dp"
android:layout_centerHorizontal="true"
android:layout_centerInParent="true"
android:layout_gravity="center_horizontal"
android:adjustViewBounds="true"
android:background="#drawable/gray_circle"
android:padding="15dp"
android:scaleType="centerCrop"
android:src="#drawable/school" />
<TextView
android:id="#+id/tv_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignEnd="#id/iv_icon"
android:layout_alignLeft="#id/iv_icon"
android:layout_alignRight="#id/iv_icon"
android:layout_alignStart="#id/iv_icon"
android:layout_below="#id/iv_icon"
android:layout_gravity="center_horizontal"
android:gravity="center"
android:text="Your Favourite Place"
android:textColor="#android:color/black" />
</RelativeLayout>
</android.support.v7.widget.CardView>