I was able to put the banner in recylerview, but it is overlapping one of the items, it replaces one, instead of getting between them, does anyone know how to fix it?
I'm pulling an api, I do not know if that makes any difference. I searched for several tutorials, but I did not find it, what I need to do is add an admob native banner.
public class HistoricoAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
List<Capitulos> capitulos;
Context context;
private static final int DEFAULT_VIEW_TYPE = 0;
private static final int NATIVE_AD_VIEW_TYPE = 1;
public HistoricoAdapter(List<Capitulos> capitulos, Context context) {
this.capitulos = capitulos;
this.context = context;
}
#Override
public int getItemViewType(int position) {
if (position>1 && position % 3 == 0) {
return NATIVE_AD_VIEW_TYPE;
}
return DEFAULT_VIEW_TYPE;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view;
LayoutInflater layoutInflater = LayoutInflater.from(context);
switch (viewType) {
default:
view = layoutInflater
.inflate(R.layout.row_historico, parent, false);
return new MyViewHolder(view);
case NATIVE_AD_VIEW_TYPE:
view = layoutInflater.inflate(R.layout.ad_unified, parent, false);
return new NativeAdViewHolder(view);
}
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (!(holder instanceof MyViewHolder)) {
return;
}
MyViewHolder holder2 = (MyViewHolder) holder;
Capitulos l = capitulos.get(position);
int aInt = Integer.parseInt(l.getTempo());
Calendar cal = Calendar.getInstance(Locale.ENGLISH);
cal.setTimeInMillis(aInt * 1000L);
String dataFormato = android.text.format.DateFormat.format("dd-MM-yyyy HH:mm:ss", cal).toString();
SpannableString ultimoLido = new SpannableString("Último lido: " + l.getCapitulo());
ultimoLido.setSpan(new StyleSpan(Typeface.BOLD), 0, "Último lido: ".length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
SpannableString data = new SpannableString("Data: " + dataFormato);
data.setSpan(new StyleSpan(Typeface.BOLD), 0, "Data: ".length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
holder2.titulo.setText(l.getTitle());
holder2.ultimoLido.setText(ultimoLido);
holder2.data.setText(data);
Picasso.get()
.load("http://unionmangas.site/assets/uploads/mangas/" + l.getCapa())
.into(holder2.capaView);
}
#Override
public int getItemCount() {
return capitulos.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView titulo;
TextView ultimoLido;
TextView data;
ImageView capaView;
public MyViewHolder(View itemView) {
super(itemView);
titulo = itemView.findViewById(R.id.tituloHistoricoViewID);
ultimoLido = itemView.findViewById(R.id.ultimosLidosViewID);
data = itemView.findViewById(R.id.dataViewID);
capaView = itemView.findViewById(R.id.capaHistoricoViewID);
}
}
public class NativeAdViewHolder extends RecyclerView.ViewHolder {
public AdView mAdView;
public NativeAdViewHolder(View view) {
super(view);
mAdView = (AdView) view.findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.build();
mAdView.loadAd(adRequest);
}
}}
Edited answer to ignore the banner click event
Issue is with getItemCount. As you are adding ads in between items you also need to increase the count as well. So that the number of items not get replaced with ad item.
public static final int ITEM_PER_AD = 3;
#Override
public int getItemCount() {
int itemCount = capitulos.size();
itemCount += itemCount / ITEM_PER_AD ;
return itemCount;
}
Accordingly you also need to exclude positions for ads, to get the original item position.
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (!(holder instanceof MyViewHolder)) {
return;
}
int itemPosition = position - position / ITEM_PER_AD ; // need to adjust to get the list item position excluding ads
}
Below code is about to ignore click event for the ads.
#Override
public void onItemClick(View view, int position) {
if (position>1 && position % ITEM_PER_AD == 0) {
return;
}
// rest of the code keep as it is.
}
Related
I have been trying to figure it out for a few days now and I still can't solve it.
I created a 3-layer nested recycler view and the display is okay.
1st layer is CartStoreAdapter
2nd layer is for it's CartItemAdapter
3rd layer is for the product's CartItemAddonAdapter
My problem is that. I want to display the total price of all the products per store(including the addon prices) considering the qty aswell. But I can't seem to pass the total Price variable (
totalItems += subTotal;
) to the CartStoreAdapter.
I tried creating a public method within the CartItemAdapter. When I use Log.d within the viewholder of CartItemAdapter,
2023-02-02 17:25:36.773 19606-19606/ph.kaminarigo.app D/totalItems: 522.0
2023-02-02 17:25:37.028 19606-19606/ph.kaminarigo.app D/totalItems: 532.0
2023-02-02 17:25:37.120 19606-19606/ph.kaminarigo.app D/totalItems: 660.0
2023-02-02 17:25:37.178 19606-19606/ph.kaminarigo.app D/totalItems: 1485.0
2023-02-02 17:25:37.230 19606-19606/ph.kaminarigo.app D/totalItems: 1785.0
shows up properly. But when I use the variable in the method. It's already zero even before I access that method in the CartStoreAdapter.
public class CartStoreAdapter extends RecyclerView.Adapter<CartStoreAdapter.ItemRowHolder> {
private List<CartStoreModel> storeDataList;
private Context mContext;
private int rowLayout;
private CartItemAdapter cartItemAdapter;
public CartStoreAdapter(List<CartStoreModel> storeDataList, Context mContext, int rowLayout) {
this.storeDataList = storeDataList;
this.mContext = mContext;
this.rowLayout = rowLayout;
}
#NonNull
#Override
public CartStoreAdapter.ItemRowHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(rowLayout, parent, false);
return new ItemRowHolder(v);
}
#Override
public void onBindViewHolder(#NonNull CartStoreAdapter.ItemRowHolder holder, int position) {
final CartStoreModel singleItem = storeDataList.get(position);
holder.bind(singleItem);
}
#Override
public int getItemCount() {
return (null != storeDataList ? storeDataList.size() : 0);
}
public class ItemRowHolder extends RecyclerView.ViewHolder{
TextView tvStoreName, tvStoreTotal;
RecyclerView rvStoreItems;
public ItemRowHolder(#NonNull View itemView) {
super(itemView);
tvStoreName = itemView.findViewById(R.id.tvStoreName);
rvStoreItems = itemView.findViewById(R.id.rvStoreItems);
tvStoreTotal = itemView.findViewById(R.id.tvStoreTotal);
}
public void bind(CartStoreModel singleItem){
tvStoreName.setText(String.valueOf(singleItem.getNama_merchant()));
CartItemAdapter cartItemAdapter = new CartItemAdapter(singleItem.getCartItem(), mContext, R.layout.cart_item);
rvStoreItems.setAdapter(cartItemAdapter);
rvStoreItems.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
double total = cartItemAdapter.getTotalItems();
Utility.currencyTXT(tvStoreTotal, String.valueOf(total), mContext);
}
}
}
public class CartItemAdapter extends RecyclerView.Adapter<CartItemAdapter.ItemRowHolder> {
private List<CartItemModel> itemDataList;
private Context mContext;
private int rowLayout;
private double totalItems;
public CartItemAdapter(List<CartItemModel> itemDataList, Context mContext, int rowLayout) {
this.itemDataList = itemDataList;
this.mContext = mContext;
this.rowLayout = rowLayout;
}
#NonNull
#Override
public CartItemAdapter.ItemRowHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(rowLayout, parent, false);
return new ItemRowHolder(v);
}
#Override
public void onBindViewHolder(#NonNull CartItemAdapter.ItemRowHolder holder, int position) {
final CartItemModel singleItem = itemDataList.get(position);
holder.bind(singleItem);
}
#Override
public int getItemCount() {
return (null != itemDataList ? itemDataList.size() : 0);
}
public double getTotalItems(){
return totalItems;
}
public class ItemRowHolder extends RecyclerView.ViewHolder{
TextView tvProductTitle, tvMainPrice, tvPromoPrice, tvSubTotal, tvQty;
ImageView imgThumbnail;
RecyclerView rvCartItemVar;
Button btnDeduct, btnAdd;
CheckBox cbSelectItem;
public ItemRowHolder(#NonNull View itemView) {
super(itemView);
tvProductTitle = itemView.findViewById(R.id.tvProductTitle);
tvMainPrice = itemView.findViewById(R.id.tvMainPrice);
tvPromoPrice = itemView.findViewById(R.id.tvPromoPrice);
imgThumbnail = itemView.findViewById(R.id.imgThumbnail);
rvCartItemVar = itemView.findViewById(R.id.rvCartItemVar);
tvSubTotal = itemView.findViewById(R.id.tvSubTotal);
btnAdd = itemView.findViewById(R.id.btnAdd);
btnDeduct = itemView.findViewById(R.id.btnDeduct);
tvQty = itemView.findViewById(R.id.tvQty);
cbSelectItem = itemView.findViewById(R.id.cbSelectItem);
}
public void bind(final CartItemModel singleItem){
CartItemAddonAdapter cartItemAddonAdapter = new CartItemAddonAdapter(singleItem.getCartItemVar(), mContext, R.layout.cart_item_variation);
rvCartItemVar.setAdapter(cartItemAddonAdapter);
rvCartItemVar.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
double activePrice, promoPrice, addOnPrice, itemCost, subTotal;
int itemQty = singleItem.getQty();
if(Constants.use_glide) {
Glide.with(mContext)
.load(Constants.IMAGESITEM + singleItem.getFoto_item())
.apply(new RequestOptions().override(250, 250))
.into(imgThumbnail);
} else {
Picasso.with(mContext)
.load(Constants.IMAGESITEM + singleItem.getFoto_item())
.placeholder(R.drawable.image_placeholder)
.resize(250, 250)
.into(imgThumbnail);
}
if(singleItem.getHarga_promo() > 0){
promoPrice = singleItem.getHarga_item();
activePrice = singleItem.getHarga_promo();
tvPromoPrice.setPaintFlags(tvPromoPrice.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
tvPromoPrice.setTextColor(Color.LTGRAY);
} else {
promoPrice = 0;
activePrice = singleItem.getHarga_item();
tvPromoPrice.setVisibility(View.GONE);
}
addOnPrice = cartItemAddonAdapter.getTotalAddonPrice();
itemCost = activePrice + addOnPrice;
subTotal = itemCost * itemQty;
totalItems += subTotal;
tvProductTitle.setText(String.valueOf(singleItem.getNama_item()));
tvQty.setText(String.valueOf(itemQty));
Utility.currencyTXT(tvMainPrice, String.valueOf(activePrice), mContext);
Utility.currencyTXT(tvPromoPrice, String.valueOf(promoPrice), mContext);
Utility.currencyTXT(tvSubTotal, String.valueOf(subTotal), mContext);
Log.d("totalItems", String.valueOf(totalItems));
}
}
}
public class CartItemAddonAdapter extends RecyclerView.Adapter<CartItemAddonAdapter.ItemRowHolder> {
private List<CartItemVarModel> addOnsDataList;
private Context mContext;
private int rowLayout;
public CartItemAddonAdapter(List<CartItemVarModel> addOnsDataList, Context mContext, int rowLayout) {
this.addOnsDataList = addOnsDataList;
this.mContext = mContext;
this.rowLayout = rowLayout;
}
#NonNull
#Override
public CartItemAddonAdapter.ItemRowHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(rowLayout,parent,false);
return new ItemRowHolder(v);
}
#Override
public void onBindViewHolder(#NonNull CartItemAddonAdapter.ItemRowHolder holder, int position) {
final CartItemVarModel singleItem = addOnsDataList.get(position);
holder.bind(singleItem);
}
#Override
public int getItemCount() {
return (null != addOnsDataList ? addOnsDataList.size() : 0);
}
public double getTotalAddonPrice() {
double totalAddonPrice = 0;
for(CartItemVarModel addon : addOnsDataList){
totalAddonPrice += addon.getVar_price();
}
return totalAddonPrice;
}
public class ItemRowHolder extends RecyclerView.ViewHolder{
TextView tvVarGroup, tvItemVar, tvPrice;
public ItemRowHolder(#NonNull View itemView) {
super(itemView);
tvVarGroup = itemView.findViewById(R.id.tvVarGroup);
tvItemVar = itemView.findViewById(R.id.tvItemVar);
tvPrice = itemView.findViewById(R.id.tvPrice);
}
public void bind(CartItemVarModel dataList){
tvVarGroup.setText(dataList.getGroup_name());
tvItemVar.setText(dataList.getVar_name());
Utility.currencyTXT(tvPrice, String.valueOf(dataList.getVar_price()), mContext);
}
}
}
I also tried to save the changes in the model but I still can't access it outside of the itemviewholder.
I would try to create the CartStoreModel items with the total prices inside each item and initialize them before I pass them to CartStoreAdapter.
Recommend to use ViewModel to calculate the prices and attach them to CartStoreModel items before you send them to CartStoreAdapter.
public class StoreViewModel extends ViewModel {
public ArrayList<CartStoreModel> getItemsWithPrices(){
for(CartStoreModel item : items) {
int totalItemPrice = item.price;
int totalItemAddonPrices = item.getTotalAddonsPrices()// calculate the prices
item.totalPrices = totalItemPrice + totalItemAddonPrices
}
}
}
Recommend to do it in another Thread (not the Main Thread) in case you have a lot of items in your list...
I have adapted class like this
public class InboxAdapter extends RecyclerView.Adapter<InboxAdapter.ViewHolder> {
private static final String LOG_TAG = InboxAdapter.class.getSimpleName();
private List<inbox> mInboxes;
private Context context;
public InboxAdapter(List<inbox> inboxes) {
mInboxes = inboxes;
}
#Override
public InboxAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
View contactView = inflater.inflate(R.layout.recyclerview_mail_item, parent, false);
ViewHolder viewHolder = new ViewHolder(contactView);
return viewHolder;
}
#Override
public void onBindViewHolder(InboxAdapter.ViewHolder holder, int position) {
inbox inbox = mInboxes.get(position);
holder.tvIcon.setText(inbox.getName().substring(0,1).toUpperCase());
holder.tvEmailSender.setText(inbox.getFrom());
holder.tvEmailTitle.setText(inbox.getSubject());
}
#Override
public int getItemCount() {
return mInboxes.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView tvIcon;
public TextView tvEmailSender;
public TextView tvEmailTitle;
public TextView tvEmailDetails;
public TextView tvEmailTime;
public ViewHolder(View itemView) {
super(itemView);
tvIcon = itemView.findViewById(R.id.tvIcon);
tvEmailSender = itemView.findViewById(R.id.tvEmailSender);
tvEmailTitle = itemView.findViewById(R.id.tvEmailTitle);
tvEmailDetails = itemView.findViewById(R.id.tvEmailDetails);
tvEmailTime = itemView.findViewById(R.id.tvEmailTime);
}
}
private int getRandomMaterialColor(String typeColor) {
int returnColor = Color.GRAY;
int arrayId =getResources().getIdentifier("mdcolor_" + typeColor, "array", getPackageName());
if (arrayId != 0) {
TypedArray colors = getResources().obtainTypedArray(arrayId);
int index = (int) (Math.random() * colors.length());
returnColor = colors.getColor(index, Color.GRAY);
colors.recycle();
}
return returnColor;
}
}
Its working fine but I want set different color for my view holder text so I have added function in it called getRandomMaterialColor. But its using getResources inside it and I am not able to use getActivity. Anyone here can please help me for solve puzzle for me? Thanks!
You can use the view(itemView) in ViewHolder Class for get the resources, for example:
private int getRandomMaterialColor(View view,String typeColor) {
int returnColor = Color.GRAY;
int arrayId =view.getResources().getIdentifier("mdcolor_" + typeColor, "array", getPackageName());
if (arrayId != 0) {
TypedArray colors = view.getResources().obtainTypedArray(arrayId);
int index = (int) (Math.random() * colors.length());
returnColor = colors.getColor(index, Color.GRAY);
colors.recycle();
}
return returnColor;
}
recyclerview.onbindviewholder always in position 0
public class NoteAdapter extends RecyclerView.Adapter<NoteAdapter.ViewHolder> {
public static final int UNCOMPLETED = 0;
public static final int COMPLETED = 1;
public static final int HIGHTLIGHT = 2;
public static final int HIGHTLIGHT_COMPETED = 3;
Cursor cursor;
Context context;
public NoteAdapter(Context context, Cursor cursor) {
this.context = context;
this.cursor = cursor;
}
public Cursor getCursor() {
return this.cursor;
}
public void setCursor(Cursor cursor) {
this.cursor = cursor;
}
public Context getContext() {
return context;
}
public void setContext(Context context) {
this.context = context;
}
#Override
public int getItemViewType(int position) {
if (cursor.moveToPosition(position)) {
cursor.move(position);
String content = cursor.getString(cursor.getColumnIndex(DatabaseHandler.KEY_CONTENT));
int completed = cursor.getInt(cursor.getColumnIndex(DatabaseHandler.KEY_COMPLETED));
int hightlight = cursor.getInt(cursor.getColumnIndex(DatabaseHandler.KEY_HIGHTLIGHT));
if (completed == 1) {
if (hightlight == 1) {
return HIGHTLIGHT_COMPETED;
}
return COMPLETED;
}
if (hightlight == 1 && completed == 0) {
return HIGHTLIGHT;
}
return UNCOMPLETED;
}
return -1;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.item_row, parent, false);
switch (viewType) {
case UNCOMPLETED:
view = inflater.inflate(R.layout.item_row, parent, false);
break;
case COMPLETED:
view = inflater.inflate(R.layout.item_row_completed, parent, false);
break;
case HIGHTLIGHT:
view = inflater.inflate(R.layout.item_row_hightlight, parent, false);
break;
case HIGHTLIGHT_COMPETED:
view = inflater.inflate(R.layout.item_row_hightlight_completed, parent, false);
break;
}
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, int position) {
if (!cursor.moveToPosition(position)) {
return;
}
String content = cursor.getString(cursor.getColumnIndex(DatabaseHandler.KEY_CONTENT));
Date date = Utilities.stringToDate(cursor.getString(cursor.getColumnIndex(DatabaseHandler.KEY_DEADLINE)));
int completed = cursor.getInt(cursor.getColumnIndex(DatabaseHandler.KEY_COMPLETED));
holder.tvContent.setText(content);
holder.tvDate.setText(Utilities.dateToString(date));
if(completed == 1){
holder.imgIcon.performClick();
}
}
#Override
public int getItemCount() {
return (cursor.getCount());
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView tvContent;
TextView tvDate;
ImageButton imgIcon;
public ViewHolder(#NonNull final View itemView) {
super(itemView);
tvContent = itemView.findViewById(R.id.tvContent);
tvDate = itemView.findViewById(R.id.tvDate);
imgIcon = itemView.findViewById(R.id.imgCheck);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int position = getAdapterPosition();
cursor.move(position);
Note note = Utilities.cursorToNote(cursor);
Intent intent = new Intent(itemView.getContext(), AddNoteActivity.class);
intent.putExtras(note.sendNoteBundle());
intent.putExtra("type", true);
itemView.getContext().startActivity(intent);
}
});
}
}
}
The program does not contain any errors.
When I run the program, it always only shows the element at the 0 position, the remaining positions do not show.
function getItemCount works normally, returning 20 elements.
English is not my native language, sorry for any grammatical errors. Thanks, everyone.
Make sure the android:layout_height for your parent layout in the layout(xml) files for the various ViewHolders has been set to wrap_content instead of match_parent.
Can someone help me with this error that I keep getting? The program that I'm trying to implement admob banner ad between items in recyclerview. every thing is ok but still this one error that blocked me from go on.
public class RecipeAdapter extends RecyclerView.Adapter<RecipeAdapter.ViewHolder> {
public static final String TAG = RecipeAdapter.class.getSimpleName();
public static final HashMap<String, Integer> LABEL_COLORS = new HashMap<String, Integer>() {{
put("Low-Carb", R.color.colorLowCarb);
put("Low-Fat", R.color.colorLowFat);
put("Low-Sodium", R.color.colorLowSodium);
put("Medium-Carb", R.color.colorMediumCarb);
put("Vegetarian", R.color.colorVegetarian);
put("Balanced", R.color.colorBalanced);
}};
private Context mContext;
private LayoutInflater mInflater;
private ArrayList<Recipe> mDataSource;
private static final int DEFAULT_VIEW_TYPE = 1;
private static final int NATIVE_AD_VIEW_TYPE = 2;
public RecipeAdapter(Context context, ArrayList<Recipe> items) {
mContext = context;
mDataSource = items;
mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); }
#Override public int getItemViewType(int position) {
// Change the position of the ad displayed here. Current is after 5
if ((position + 1) % 6 == 0) {
return NATIVE_AD_VIEW_TYPE;
}
return DEFAULT_VIEW_TYPE; }
#NonNull
#Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view;
LayoutInflater layoutInflater = LayoutInflater.from(mContext);
switch (viewType) {
default:
view = layoutInflater
.inflate(R.layout.list_item_native_ad, parent, false);
return new ViewHolder(view);
case NATIVE_AD_VIEW_TYPE:
view = layoutInflater.inflate(R.layout.list_item_native_ad, parent, false);
return new ViewHolderAdMob(view);
}
}
#Override public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
// Get relevant subviews of row view
TextView titleTextView = holder.titleTextView;
TextView subtitleTextView = holder.subtitleTextView;
TextView detailTextView = holder.detailTextView;
ImageView thumbnailImageView = holder.thumbnailImageView;
//Get corresponding recipe for row final Recipe recipe = (Recipe) getItem(position);
// Update row view's textviews to display recipe information
titleTextView.setText(recipe.title);
subtitleTextView.setText(recipe.description);
detailTextView.setText(recipe.label);
// Use Picasso to load the image. Temporarily have a placeholder in case it's slow to load
Picasso.with(mContext).load(recipe.imageUrl).placeholder(R.mipmap
.ic_launcher).into(thumbnailImageView);
holder.parentView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent detailIntent = new Intent(mContext, RecipeDetailActivity.class);
detailIntent.putExtra("title", recipe.title);
detailIntent.putExtra("url", recipe.instructionUrl);
mContext.startActivity(detailIntent);
}
});
// Style text views
Typeface titleTypeFace = Typeface.createFromAsset(mContext.getAssets(),
"fonts/JosefinSans-Bold.ttf");
titleTextView.setTypeface(titleTypeFace);
Typeface subtitleTypeFace = Typeface.createFromAsset(mContext.getAssets(),
"fonts/JosefinSans-SemiBoldItalic.ttf");
subtitleTextView.setTypeface(subtitleTypeFace);
Typeface detailTypeFace = Typeface.createFromAsset(mContext.getAssets(),
"fonts/Quicksand-Bold.otf");
detailTextView.setTypeface(detailTypeFace);
detailTextView.setTextColor(android.support.v4.content.ContextCompat.getColor(mContext, LABEL_COLORS
.get(recipe.label)));
}
#Override public int getItemCount() {
return mDataSource.size(); }
#Override public long getItemId(int position) {
return position; }
public Object getItem(int position) {
return mDataSource.get(position); }
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView titleTextView;
private TextView subtitleTextView;
private TextView detailTextView;
private ImageView thumbnailImageView; private View parentView;
public ViewHolder(#NonNull View view){
super(view);
// create a new "Holder" with subviews
this.parentView = view;
this.thumbnailImageView = (ImageView) view.findViewById(R.id.recipe_list_thumbnail);
this.titleTextView = (TextView) view.findViewById(R.id.recipe_list_title);
this.subtitleTextView = (TextView) view.findViewById(R.id.recipe_list_subtitle);
this.detailTextView = (TextView) view.findViewById(R.id.recipe_list_detail);
// hang onto this holder for future recyclage
view.setTag(this);
}
}
public class ViewHolderAdMob extends RecyclerView.ViewHolder {
private final AdView mNativeAd;
public ViewHolderAdMob(View itemView) {
super(itemView);
mNativeAd = itemView.findViewById(R.id.nativeAd);
mNativeAd.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
super.onAdLoaded();
// if (mItemClickListener != null) {
Log.i("AndroidBash", "onAdLoaded");
// }
}
#Override
public void onAdClosed() {
super.onAdClosed();
// if (mItemClickListener != null) {
Log.i("AndroidBash", "onAdClosed");
// }
}
#Override
public void onAdFailedToLoad(int errorCode) {
super.onAdFailedToLoad(errorCode);
// if (mItemClickListener != null) {
Log.i("AndroidBash", "onAdFailedToLoad");
// }
}
#Override
public void onAdLeftApplication() {
super.onAdLeftApplication();
// if (mItemClickListener != null) {
Log.i("AndroidBash", "onAdLeftApplication");
// }
}
#Override
public void onAdOpened() {
super.onAdOpened();
// if (mItemClickListener != null) {
Log.i("AndroidBash", "onAdOpened");
// }
}
});
AdRequest adRequest = new AdRequest.Builder()
.addTestDevice("") // Remove this before publishing app
.build();
mNativeAd.loadAd(adRequest);
}
}
}
The return type needs to be whatever ViewHolder type you declared for your adapter class.
For example, from the Android RecyclerView example page:
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
// ^^^^^^^^^^^^^^^^^^^^^^
// It should return this type ^
public static class MyViewHolder extends RecyclerView.ViewHolder {
// your adapter
}
#Override
public MyAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent,int viewType) {
// Note: returns MyAdapter.MyViewHolder, not RecyclerView.ViewHolder
}
}
In your case, you have
public class RecipeAdapter extends RecyclerView.Adapter<RecipeAdapter.ViewHolder>
which means your onCreateViewHolder has to return RecipeAdapter.ViewHolder not RecyclerView.ViewHolder.
There is a separate issue too, which is that you have two ViewHolder types in the same adapter. To do this, you would need to change the ViewHolder type that your RecyclerView is based on to the generic type (RecyclerView.ViewHolder).
Please review this question, it has good answers for how to do this.
I'm creating RecycleView with some items. So I need to get the width and height of the one row of RecycleView
Here I'm creating RecycleView:
RecyclerView rvSmetki = (RecyclerView) findViewById(R.id.rvArtikli);
rvSmetki.setLayoutManager(new GridLayoutManager(this, 3););
rvSmetki.setAdapter(new ArtikliAdapter(this));
// Here I want to get width and height....
And this is my ArtikliAdapter:
public class ArtikliAdapter extends RecyclerView.Adapter<ArtikliAdapter.ViewHolder> {
private static Context context;
private LayoutInflater inflater;
private ArrayList<Artikl> artikliList;
public ArtikliAdapter(Context context) {
this.context = context;
inflater = LayoutInflater.from(context);
artikliList = LogInActivity.getArtiklList();
}
#Override
public ArtikliAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View row = inflater.inflate(R.layout.artikli_row, parent, false);
return new ArtikliAdapter.ViewHolder(row);
}
#Override
public void onBindViewHolder(ArtikliAdapter.ViewHolder holder, int position) {
Artikl currentArtikl = artikliList.get(position);
holder.tvNaziv.setText(currentArtikl.getNaziv());
holder.tvCena.setText("Цена: " + currentArtikl.getProdaznaCena());
}
#Override
public int getItemCount() {
return artikliList.size();
}
static class ViewHolder extends RecyclerView.ViewHolder {
private RelativeLayout rlArtikl;
private TextView tvNaziv;
private TextView tvCena;
public ViewHolder(View itemView) {
super(itemView);
rlArtikl = (RelativeLayout) itemView.findViewById(R.id.rlArtikl);
tvNaziv = (TextView) itemView.findViewById(R.id.tvNaziv);
tvCena = (TextView) itemView.findViewById(R.id.tvCena);
}
}
}
How can I get width and height of one row?
#Override
public void onBindViewHolder(final MyAdapter.MyViewHolder holder, int position)
{
.....
holder.itemView.post(new Runnable()
{
#Override
public void run()
{
int cellWidth = holder.itemView.getWidth();// this will give you cell width dynamically
int cellHeight = holder.itemView.getHeight();// this will give you cell height dynamically
}
});
.....
}
I hope this will help you!!