Android RecyclerView layout bug - android

I have a recyclerview when it displayed for the first time the child's layout are not displayed properly:
but when i scroll to bottom and come back to the top it's good :
I have the same problem when i change the layout for a larger.
This is my Adapter class (don't take in consideration the diffents type,this is not the source of the bug because the bug exist too when i have one ViewHolder type)
private class Adapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final int TYPE_ALERTS = 0 ;
private static final int TYPE_MOST_VIEWED = 1 ;
#Override
public RecyclerView.ViewHolder onCreateViewHolder (final ViewGroup parent, int viewType) {
if (viewType == TYPE_ALERTS){
View itemLayoutView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.layout_item_alerts_home_home, null);
ViewHolderAlerts viewHolderAlerts = new ViewHolderAlerts(itemLayoutView);
itemLayoutView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick (View v) {
Intent intent = new Intent(activity, Activity_UpdateAlert.class);
intent.putExtra("alert", (AlertObj)listAllProducts.get(recyclerView.getChildAdapterPosition(v)));
startActivity(intent);
}
});
return viewHolderAlerts;
}else {
View itemLayoutView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.layout_item_product_grid__list_products_by_category, null);
ViewHolder_Product_CatSearch viewHolder_product_catSearch = new ViewHolder_Product_CatSearch(itemLayoutView);
itemLayoutView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick (View v) {
Intent intent = new Intent(activity, Activity_ProductDetails.class);
intent.putExtra("product", (Product)listAllProducts.get(recyclerView.getChildAdapterPosition(v)));
startActivity(intent);
}
});
return viewHolder_product_catSearch ;
}
}
#Override
public void onBindViewHolder (RecyclerView.ViewHolder holder, int position) {
if (getItemViewType(position) == TYPE_ALERTS){
((ViewHolderAlerts)holder).textViewTitle.setText(((AlertObj)listAllProducts.get(position)).product.name);
((ViewHolderAlerts)holder).textViewPrice.setText(new DecimalFormat("###0.00")
.format(Double.valueOf(((AlertObj)listAllProducts.get(position)).product.price)) +
((AlertObj)listAllProducts.get(position)).product.currency);
Glide.with(activity.getApplicationContext())
.load(((AlertObj)listAllProducts.get(position)).product.imgUrl)
.error(R.drawable.picture_not_available)
.into(((ViewHolderAlerts) holder).imgView);
}else {
((ViewHolder_Product_CatSearch)holder).textViewName.setText(((ProductMostViews)listAllProducts.get(position)).name);
((ViewHolder_Product_CatSearch)holder).textViewPrice.setText(new DecimalFormat("###0.00")
.format(Double.valueOf(((ProductMostViews)listAllProducts.get(position)).price)) +
((ProductMostViews)listAllProducts.get(position)).currency);
Glide.with(activity.getApplicationContext())
.load(((ProductMostViews)listAllProducts.get(position)).imgUrl)
.error(R.drawable.picture_not_available)
.into(((ViewHolder_Product_CatSearch) holder).imageViewProduct);
}
}
#Override
public int getItemViewType (int position) {
return listAllProducts.get(position) instanceof AlertObj ? TYPE_ALERTS : TYPE_MOST_VIEWED ;
}
#Override
public long getItemId (int position) {
return listAllProducts.get(position) instanceof AlertObj ? TYPE_ALERTS : TYPE_MOST_VIEWED ;
}
#Override
public int getItemCount () {
return listAllProducts.size();
}
}
Thank's

Related

How to add margin to 2x2 items view in grid view?

Want to add margin to gridview in the following manner.
Left margin for 2,4, 2,9, 12,14,..
Right margin for 3,5, 8,10, 13,15,..
Here is my code snippet which I tried to set margin to 2x2 items in grid view...
i.e positions - ..,2,3,4,5,..,7,8,9,10,..,12,13,14,15,..,17,18,19,20,.. like wise.
for 2,3,4,5 & 12,13,14,15,.. Getting the expected output. but my case failed for 7,8,9,10 & 17,18,19,20 series.
Help me to solve this. Confused to solve this mathematical puzzle.
Thanks in advance.
public class BoxFeedAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private List<BoxFeedResult> boxFeedResults;
private Context mContext;
private RecyclerViewItemClickListener viewItemClickListener;
private final int LARGE_TYPE = 0;
private final int SMALL_TYPE = 1;
private final int PROGRESS_TYPE = 2;
private int GRID_VIEW_MARGIN_LEFT = 0;
private int GRID_VIEW_MARGIN_RIGHT = 0;
private int GRID_VIEW_MARGIN_TOP = 0;
private int GRID_VIEW_MARGIN_BOTTOM = 0;
private int GRID_VIEW_ROW_MARGIN = 0;
public BoxFeedAdapter(Context context, RecyclerViewItemClickListener viewItemClickListener) {
this.mContext = context;
this.viewItemClickListener = viewItemClickListener;
boxFeedResults = new ArrayList<>();
GRID_VIEW_MARGIN_LEFT = context.getResources().getDimensionPixelOffset(R.dimen.empty_dimen);
GRID_VIEW_MARGIN_RIGHT = context.getResources().getDimensionPixelOffset(R.dimen.empty_dimen);
GRID_VIEW_MARGIN_TOP = context.getResources().getDimensionPixelOffset(R.dimen.channel_row_padding);
GRID_VIEW_MARGIN_BOTTOM = context.getResources().getDimensionPixelOffset(R.dimen.empty_dimen);
GRID_VIEW_ROW_MARGIN = context.getResources().getDimensionPixelOffset(R.dimen.channel_row_padding_left);
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
if (viewType == SMALL_TYPE) {
View layoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_box_feed_series_banner, null);
return new BoxFeedSeriesListViewHolder(layoutView);
} else if (viewType == LARGE_TYPE) {
View layoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_box_feed_episode_banner, null);
return new BoxFeedEpisodeViewHolder(layoutView);
} else {
View layoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.progress_item, null);
return new ProgressViewHolder(layoutView);
}
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, final int position) {
if (holder instanceof BoxFeedSeriesListViewHolder) {
StaggeredGridLayoutManager.LayoutParams layoutParams = new StaggeredGridLayoutManager.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
layoutParams.setFullSpan(false);
if ((position - 1) % 2 == 0) {
layoutParams.setMargins(GRID_VIEW_ROW_MARGIN, GRID_VIEW_MARGIN_TOP, GRID_VIEW_MARGIN_RIGHT, GRID_VIEW_MARGIN_BOTTOM);
} else {
layoutParams.setMargins(GRID_VIEW_MARGIN_LEFT, GRID_VIEW_MARGIN_TOP, GRID_VIEW_ROW_MARGIN, GRID_VIEW_MARGIN_BOTTOM);
}
holder.itemView.setLayoutParams(layoutParams);
final BoxFeedResult singleFeed = boxFeedResults.get(position);
final BoxFeedSeriesListViewHolder viewHolder = (BoxFeedSeriesListViewHolder) holder;
Glide.with(mContext)
.load(singleFeed.getA4MediumUrl())
.placeholder(R.drawable.bg_black)
.into(viewHolder.seriesImage);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(mContext, singleFeed.getId(), Toast.LENGTH_SHORT).show();
viewItemClickListener.onItemClickListioner(singleFeed, viewHolder.seriesImage, position);
}
});
} else if (holder instanceof BoxFeedEpisodeViewHolder) {
StaggeredGridLayoutManager.LayoutParams layoutParams = new StaggeredGridLayoutManager.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
layoutParams.setFullSpan(true);
holder.itemView.setLayoutParams(layoutParams);
final BoxFeedResult singleFeed = boxFeedResults.get(position);
final BoxFeedEpisodeViewHolder viewHolder = (BoxFeedEpisodeViewHolder) holder;
Glide.with(mContext)
.load(singleFeed.getAspectMediumUrl())
.placeholder(R.drawable.bg_black)
.into(viewHolder.episodeImage);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(mContext, singleFeed.getId(), Toast.LENGTH_SHORT).show();
}
});
} else {
StaggeredGridLayoutManager.LayoutParams layoutParams = new StaggeredGridLayoutManager.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
layoutParams.setFullSpan(true);
holder.itemView.setLayoutParams(layoutParams);
}
}
#Override
public int getItemCount() {
return boxFeedResults.size();
}
#Override
public int getItemViewType(int position) {
switch (boxFeedResults.get(position).getTileType()) {
case “large":
return LARGE_TYPE;
case “small":
return SMALL_TYPE;
default:
return PROGRESS_TYPE;
}
}
public void addList(List<BoxFeedResult> feedResults) {
this.boxFeedResults = feedResults;
notifyDataSetChanged();
}
}
Expected output is

scroll recyclerview after click item of another recyclerview?

I want to scroll recyclerview by click on category position of another recyclerview which is called in popup menu...Below is my code, I am using Sectional Recyclerview and i want to get section item position while click on second recyclerview item...Please note that both recyclerview item's category id is same;
CategoryMenuRecyclerview Adapter:
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private ArrayList<MenuItem.ProductCategory> mDataset;
private ItemListner itemListner;
RestaurantMenuActivity mContext;
public MyAdapter(RestaurantMenuActivity mContext, ArrayList<MenuItem.ProductCategory> productList, ItemListner itemListner) {
mDataset = productList;
this.itemListner = itemListner;
this.mContext = mContext;
}
public class ViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
public View mainView;
TextView tvCategory, tvCategoryNo;
public ViewHolder(View v) {
super(v);
mainView = v;
tvCategory = (TextView) v.findViewById(R.id.tvCategory);
tvCategoryNo = (TextView) v.findViewById(R.id.tvCategoryNo);
}
}
// Create new views (invoked by the layout manager)
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// create a new view
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_category, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
// - get element from your dataset at this position
// - replace the contents of the view with that element
holder.tvCategory.setText(mDataset.get(position).getCategoryName());
holder.mainView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
itemListner.Item(position);
}
});
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
return mDataset.size();
}
}
and i want to scroll below adapter with click item of upper recyclerview item;
RestaurantMenuAdapter;
public class RestaurantMenuAdapter extends SectionedRecyclerViewAdapter<RecyclerView.ViewHolder> {
private List<MenuItem.ProductCategory> allData;
public RestaurantMenuAdapter(List<MenuItem.ProductCategory> data) {
this.allData = data;
}
#Override
public int getSectionCount() {
return allData == null ? 0 : allData.size();
}
private MenuItem.ProductCategory getItem(int position) {
return allData.get(position);
}
#Override
public int getItemCount(int section) {
return allData.get(section).getProductDetails() == null ? 0 : allData.get(section).getProductDetails().size();
}
#Override
public void onBindHeaderViewHolder(RecyclerView.ViewHolder holder, int section) {
String sectionName = allData.get(section).getCategoryName();
SectionViewHolder sectionViewHolder = (SectionViewHolder) holder;
sectionViewHolder.tvCategory.setText(sectionName);
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int section, final int relativePosition, int absolutePosition) {
final ItemViewHolder itemViewHolder = (ItemViewHolder) holder;
itemViewHolder.tvProductName.setText(allData.get(section).getProductDetails().get(relativePosition).getProductName());
itemViewHolder.tvDescription.setText("Grass Fed Beef with creespy bacon, tasty cheese, salad, relish and hot");
itemViewHolder.tvPrice.setText("$ " + allData.get(section).getProductDetails().get(relativePosition).getCurrentPrice());
if (near_by_restaurant) {
rlAddCart.setVisibility(View.VISIBLE);
if (tvCategoryCount.getText().toString().matches("0")) {
rlAddCart.setVisibility(View.GONE);
} else {
rlAddCart.setVisibility(View.VISIBLE);
}
if (allData.get(section).getProductDetails().get(relativePosition).getIsOpen().equalsIgnoreCase("1")) {
itemViewHolder.ll_product.setAlpha(0.5f);
itemViewHolder.ll_product.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new AlertDialog.Builder(RestaurantMenuActivity.this)
.setMessage("Sorry kitchen is closed")
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.show();
}
});
} else if (allData.get(section).getProductDetails().get(relativePosition).getIsSoldout().equalsIgnoreCase("1")) {
itemViewHolder.tvSoldOut.setVisibility(View.VISIBLE);
itemViewHolder.ll_product.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new AlertDialog.Builder(RestaurantMenuActivity.this)
.setMessage("Sorry all items are sold out")
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Your code
dialog.dismiss();
}
})
.show();
}
});
} else {
itemViewHolder.tvSoldOut.setVisibility(View.GONE);
itemViewHolder.ll_product.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SharedPreferences sharedPref = getSharedPreferences("cartitems", 0);
String strJson = sharedPref.getString("cartdata", "0");
try {
mainjsonArray = new JSONArray(strJson);
} catch (JSONException e) {
e.printStackTrace();
}
Intent i = new Intent(RestaurantMenuActivity.this, ProductCartActivity.class);
i.putExtra("product_id", allData.get(section).getProductDetails().get(relativePosition).getProductID());
i.putExtra("productCart", true);
i.putExtra("product_name", allData.get(section).getProductDetails().get(relativePosition).getProductName());
i.putExtra("product_price", allData.get(section).getProductDetails().get(relativePosition).getCurrentPrice());
try {
i.putExtra("jsonArray", mainjsonArray.toString());
} catch (Exception e) {
e.printStackTrace();
}
startActivityForResult(i, PRODUCT_CART);
}
});
}
} else {
rlAddCart.setVisibility(View.GONE);
itemViewHolder.ll_product.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new AlertDialog.Builder(RestaurantMenuActivity.this)
.setMessage("Sorry you are not in restaurant")
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Your code
dialog.dismiss();
}
})
.show();
}
});
}
if (allData.get(section).getProductDetails().get(relativePosition).getFavorited() == 0) {
itemViewHolder.ivFav.setImageResource(R.drawable.fav_02);
} else {
itemViewHolder.ivFav.setImageResource(R.drawable.favroite_highlited);
}
itemViewHolder.ivFav.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final ProgressDialog pd = ProgressDialog.show(RestaurantMenuActivity.this, "", "Loading...");
JSONObject postdata = new JSONObject();
try {
YupITApplication.getJsonWithHTTPPost(RestaurantMenuActivity.this, 1, new ServiceCallBack() {
#Override
public void serviceCallback(int id, JSONObject jsonResult) {
pd.dismiss();
try {
if (jsonResult.has("Data") && !jsonResult.getString("Data").equals("")) {
// {"Status":"Success","StatusCode":"200","Message":"Item Favourited!","Data":[]}
if (jsonResult.getString("Message").equalsIgnoreCase("Item Favourited!")) {
itemViewHolder.ivFav.setImageResource(R.drawable.favroite_highlited);
} else {
itemViewHolder.ivFav.setImageResource(R.drawable.fav_02);
}
Toast.makeText(getApplicationContext(), jsonResult.getString("Message"), Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, Utils.insertfavoriteitem + "&productid=" + allData.get(section).getProductDetails().get(relativePosition).getProductID() + "&userid=" + customer_id, postdata);
} catch (Exception e) {
e.printStackTrace();
}
}
});
Glide.with(RestaurantMenuActivity.this).load(allData.get(section).getProductDetails().get(relativePosition).getPhotoImagePath())
.thumbnail(0.5f)
.crossFade()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(itemViewHolder.ivMenu);
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, boolean header) {
View v = null;
if (header) {
v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_item_section, parent, false);
v.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
width = v.getMeasuredWidth();
height = v.getMeasuredHeight();
return new SectionViewHolder(v);
} else {
v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_item, parent, false);
return new ItemViewHolder(v);
}
}
// SectionViewHolder Class for Sections
public class SectionViewHolder extends RecyclerView.ViewHolder {
final TextView tvCategory;
public SectionViewHolder(View itemView) {
super(itemView);
tvCategory = (TextView) itemView.findViewById(R.id.tvCategory);
}
}
// ItemViewHolder Class for Items in each Section
public class ItemViewHolder extends RecyclerView.ViewHolder {
final TextView tvProductName, tvDescription, tvPrice, tvSoldOut;
LinearLayout ll_product;
ImageView ivMenu, ivFav;
public ItemViewHolder(View itemView) {
super(itemView);
tvProductName = (TextView) itemView.findViewById(R.id.tvProductName);
tvDescription = (TextView) itemView.findViewById(R.id.tvDescription);
tvPrice = (TextView) itemView.findViewById(R.id.tvPrice);
ivMenu = (ImageView) itemView.findViewById(R.id.ivMenu);
ll_product = (LinearLayout) itemView.findViewById(R.id.ll_product);
tvSoldOut = (TextView) itemView.findViewById(R.id.tvSoldOut);
ivFav = (ImageView) itemView.findViewById(R.id.ivFav);
}
}
public int isSectionHeaderPosition(int position) {
return Integer.parseInt(allData.get(position).getCategoryID());
}
}
Please help
i think that the position of category in popup menu will be the same as section value of the second recyclerView if you get the position of clicked item in your activity by listening on item's click you can scroll the recyclerView using the LayoutManager.
recyclerView.getLayoutManager().scrollToPosition(youPositionInTheAdapter).

Listview adapter bugging when refreshing list (loading new details)

I have an awards section where I load data from my server.
I'm pulling 8 by 8 awards from server and loading them in my ListView. Awards can be sold and in my adapter I have a checker where if quantity < 1 there will be a bar over Image that will notify user that award is sold.
There is lazy load where user can swipe to load more details by increasing index, so server can determine which 8 awards should he return. 1 for first 8, 2 for second 8 etc.
Problem is when I scroll to first sold award, ListView gets weird and all awards get that sold bar over their images. This is the code from activity:
public class AwardListFragment extends Fragment { int offset = 0;
int size = 8;
private int ID;
private boolean _isAwardsLoaded = false;
private SwipyRefreshLayout swipyRefreshLayout;
private ProgressDialog progressBar;
private ArrayList<Awards> listAwards;
ListView awardlist;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.rewards_section, parent, false);
awardlist = (ListView) rootView.findViewById(R.id.awardlist);
awardlist.setItemsCanFocus(true);
listAwards = new ArrayList<>();
swipyRefreshLayout = (SwipyRefreshLayout) rootView.findViewById(R.id.swipe_section_swipe);
awardlist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(getActivity(), AwardDetailsScreen.class);
ID = listAwards.get(position).getId();
Bundle bundle = new Bundle();
bundle.putInt("ID", ID);
intent.putExtras(bundle);
startActivity(intent);
}
});
return rootView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
}
public void showlist() {
progressBar = new ProgressDialog(getActivity());
progressBar.setMessage("Pls Wait...");
progressBar.show();
final int firstitemposition = 0;
final int currentposition = awardlist.getFirstVisiblePosition();
NetworkSDK.getInstance().getAwards(size, offset, new Callback<List<Awards>>() {
#Override
public void onResponse(Call<List<Awards>> call, Response<List<Awards>> response) {
if (response.code() == 401) {
Intent intent = new Intent(getContext(), MainPreLogin.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
SharedData.getInstance().removeString("token");
} else {
if (response.isSuccess()) {
if (response.body().size() == 0) {
Toast.makeText(getContext(), "All awards loaded", Toast.LENGTH_SHORT).show();
progressBar.setCancelable(false);
progressBar.dismiss();
} else
for (int i = 0; i < response.body().size(); i++)
listAwards.add(response.body().get(i));
AwardsAdapter awardsAdapter = new AwardsAdapter(listAwards);
awardlist.setAdapter(awardsAdapter);
awardsAdapter.notifyDataSetChanged();
awardlist.setSelectionFromTop(currentposition, firstitemposition);
}
progressBar.setCancelable(false);
progressBar.dismiss();
}
}
#Override
public void onFailure(Call<List<Awards>> call, Throwable t) {
Toast.makeText(getContext(), R.string.errorNoconnection, Toast.LENGTH_LONG).show();
progressBar.dismiss();
}
});
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser && !_isAwardsLoaded) {
swipyRefreshLayout.setOnRefreshListener(new SwipyRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh(SwipyRefreshLayoutDirection direction) {
if (direction == SwipyRefreshLayoutDirection.BOTTOM) {
offset++;
swipyRefreshLayout.setRefreshing(false);
showlist();
}
}
showlist();
});
}
}
}
This is my adapter.
public class AwardsAdapter extends BaseAdapter {
ArrayList<Awards> awards;
public AwardsAdapter(ArrayList<Awards> awards) {
this.awards = awards;
}
public void clearData() {
// clear the data
awards.clear();
}
#Override
public int getCount() {
return awards.size();
}
#Override
public Object getItem(int position) {
return awards.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = null;
Integer identity;
ViewHolder viewHolder = null;
if (convertView == null) {
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.award_item, parent, false);
viewHolder = new ViewHolder(view);
view.setTag(viewHolder);
} else {
view = convertView;
viewHolder = (ViewHolder) view.getTag();
}
Awards awards = (Awards) getItem(position);
if (awards != null) {
identity = awards.getId();
viewHolder.name.setText(awards.getName().toUpperCase());
viewHolder.price.setText("Money amount: " + awards.getPriceAmount().toString() );
viewHolder.points.setText("Points amount :" + awards.getCreditAmount().toString());
if (awards.getImagePath().isEmpty())
Picasso.with(view.getContext()).load(R.drawable.placeholder).fit().centerCrop().into(viewHolder.picture);
else
Picasso.with(view.getContext()).load(awards.getImagePath()).fit().centerCrop().into(viewHolder.picture);
if (awards.getQuantity()<1)
Picasso.with(view.getContext()).load(R.drawable.sold).into(viewHolder.checker);
else
if (awards.getIsVip())
Picasso.with(view.getContext()).load(R.drawable.vip).into(viewHolder.checker);
}
return view;
}
private class ViewHolder {
TextView name;
TextView price;
TextView points;
ImageView picture;
ImageView checker;
public ViewHolder(View view) {
this.name = (TextView) view.findViewById(R.id.award_name);
this.price = (TextView) view.findViewById(R.id.award_price);
this.picture = (ImageView) view.findViewById(R.id.award_picture);
this.points = (TextView) view.findViewById(R.id.award_points);
this.checker=(ImageView)view.findViewById(R.id.checker);
}
}
}
In your adapter's getView(), you have this piece of code:
if (awards.getQuantity()<1)
Picasso.with(view.getContext()).load(R.drawable.sold).into(viewHolder.checker);
else
if (awards.getIsVip())
Picasso.with(view.getContext()).load(R.drawable.vip).into(viewHolder.checker);
Change it to something like this (it depends on how you want to show/hide your view. As it stands, you're not handling the case where you need to hide it!):
if (awards.getQuantity()<1) {
Picasso.with(view.getContext()).load(R.drawable.sold).into(viewHolder.checker);
}
else {
// hide viewHolder.checker here
}
if (awards.getIsVip()) {
Picasso.with(view.getContext()).load(R.drawable.vip).into(viewHolder.checker);
}
Note: As a general piece of advice, always use curly brackets to avoid such bugs and confusion.

How to change text of child view onclick of recycler view?

I have it clicked and it gets up to it and shows the right getText() method but the setText method is not working...
userAdapter.setOnEntryClickListener(new UserAdapter.OnEntryClickListener() {
#Override
public void onEntryClick(View view, int position) {
DatabaseUser user = dbUsersList.get(position);
TextView clickedView = (TextView) view.findViewById(R.id.userAdapterFollowBtn);
if(view == clickedView) {
if (clickedView.getText().equals("following")) {
Log.d(Constants.DEBUG, " THE CLICK VIEW IS " + clickedView.getText());
//APPLY Following
String txtFollow = "follow";
clickedView.setText(txtFollow);
if (user.getIsChanged() == 0) {
user.setIsChanged(1);
} else {
user.setIsChanged(0);
}
user.setIsType(3);
db.updateFollow(user);
userAdapter.notifyDataSetChanged();
} else {
clickedView.setText("following");
if (user.getIsChanged() == 0) {
user.setIsChanged(1);
} else {
user.setIsChanged(0);
}
user.setIsType(0);
db.updateFollow(user);
userAdapter.notifyDataSetChanged();
}
} else {
Toast.makeText(getApplicationContext(), user.getUsername() + " is selected!", Toast.LENGTH_SHORT).show();
takeToUserProfile(dbUsersList.get(position));
}
}
});
Here is the adapter class:
public class UserAdapter extends RecyclerView.Adapter<UserAdapter.MyViewHolder> {
private List<DatabaseUser> dbUsersList, followingList;
private DatabaseHelper db;
private Context context;
private Typeface typeFace, italicTypeface, boldTypeface;
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public TextView userAdapterUsername, userAdapterFollowBtn;
public ImageView userAdapterUserPicture;
public MyViewHolder(View view) {
super(view);
userAdapterUsername = (TextView) view.findViewById(R.id.userAdapterUsername);
userAdapterFollowBtn = (TextView) view.findViewById(R.id.userAdapterFollowBtn);
userAdapterUserPicture = (ImageView) view.findViewById(R.id.userAdapterUserPicture);
Log.d(Constants.DEBUG, "IN MY VIEW HOLDER");
view.setOnClickListener(this);
userAdapterFollowBtn.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (mOnEntryClickListener != null) {
Log.d(Constants.DEBUG, "IN On click");
mOnEntryClickListener.onEntryClick(v, getAdapterPosition());
}
}
}
private static OnEntryClickListener mOnEntryClickListener;
public interface OnEntryClickListener {
void onEntryClick(View view, int position);
}
public void setOnEntryClickListener(OnEntryClickListener onEntryClickListener) {
mOnEntryClickListener = onEntryClickListener;
}
public UserAdapter(Context mContext, List<DatabaseUser> usersList, List<DatabaseUser> passedFollowing, Typeface myTypeface, Typeface myTypefaceItalic, Typeface myTypefaceBold) {
context = mContext;
dbUsersList = usersList;
followingList = passedFollowing;
typeFace = myTypeface;
italicTypeface = myTypefaceItalic;
boldTypeface = myTypefaceBold;
Log.d(Constants.DEBUG, "IN MY User ADAPTER CONSTRUCTOR");
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.follow_item, parent, false);
Log.d(Constants.DEBUG, "RETURN ITEM VIEW HOLDER");
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(final MyViewHolder holder, int position) {
DatabaseUser user = dbUsersList.get(position);
holder.userAdapterUsername.setTypeface(boldTypeface);
holder.userAdapterUsername.setText(user.getUsername());
final int pos = getItemViewType(position);
//TODO Create pic link
if(containsId(dbUsersList.get(pos), followingList)) {
//Then show following
holder.userAdapterFollowBtn.setText("following");
} else {
//show follow
holder.userAdapterFollowBtn.setText("follow");
}
String userspic = dbUsersList.get(pos).getPicture();
if(userspic == null) {
//SET DEFAULT OR PUT DEFAULT IN XML AND DO NOTHING IT SHOULD SHOW DEFAULT PIC
} else {
//TODO setupUser Pic
String img1 = "http://www.hindustantimes.com/Images/popup/2015/6/kungfu2.jpg";
Picasso.with(context).load(img1).transform(new RoundedTransformation()).into(holder.userAdapterUserPicture);
}
}
#Override
public int getItemCount() {
return dbUsersList.size();
}
public static boolean containsId(DatabaseUser currentUser, List<DatabaseUser> list) {
for (DatabaseUser object : list) {
if (currentUser.getUserId().equals(object.getUserId())) {
return true;
}
}
return false;
}
#Override
public int getItemViewType(int position) {
return position;
}
}
your dbUsersList is not updating. please check your user object in dbUsersList after notify data set change.
What ended up being the problem is that I had passed in the followingList, so I never re-called to grab the new following from the db on update. The update was happening I just had to re-grab the followingList from the db to have an updated list to check against like so in a new method that was passing the list back to the contains method.
db.grabFollowersList();

How to change text color when click item of RecylerView in android

This is Adapter!
public class CategoryAdapter extends RecyclerView.Adapter<CategoryAdapter.CategoryAdapterObjectHolder> {
private static String LOG_TAG = "CategoryAdapter";
private List<Category> mCategory;
private static MyClickListener myClickListener;
public static class CategoryAdapterObjectHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView mTextTitle;
public CategoryAdapterObjectHolder(View itemView) {
super(itemView);
mTextTitle = (TextView) itemView.findViewById(R.id.text_menu);
DebugTool.logD(LOG_TAG + "Adding Listener");
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
myClickListener.onItemClick(getPosition(), v);
}
}
public void setOnItemClickListener(MyClickListener myClickListener) {
this.myClickListener = myClickListener;
}
public CategoryAdapter(List<Category> myHistoryData) {
mCategory = myHistoryData;
}
#Override
public CategoryAdapter.CategoryAdapterObjectHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_menu, parent, false);
CategoryAdapterObjectHolder dataObjectHolder = new CategoryAdapterObjectHolder(view);
return dataObjectHolder;
}
#Override
public void onBindViewHolder(CategoryAdapter.CategoryAdapterObjectHolder holder, int position) {
holder.mTextTitle.setText(mCategory.get(position).getName());
}
public void addItem(Category dataObj, int index) {
mCategory.add(dataObj);
notifyItemInserted(index);
}
public void deleteItem(int index) {
mCategory.remove(index);
notifyItemRemoved(index);
}
#Override
public int getItemCount() {
return mCategory.size();
}
public interface MyClickListener {
public void onItemClick(int position, View v);
}
}
This is OnItemClick
#Override
public void onResume() {
super.onResume();
((CategoryAdapter) adapter).setOnItemClickListener(
new CategoryAdapter.MyClickListener() {
#Override
public void onItemClick(int position, View v) {
TextView mTextItem = (TextView) v.findViewById(R.id.text_menu);
// mTextItem.setTextColor(getResources().getColor(R.color.color_text_white));
if (position == 0) {
Utils.showToast(getContext(), "POSITION 0");
} else if (position == 1) {
Utils.showToast(getContext(), "POSITION 1");
} else if (position == 2) {
Utils.showToast(getContext(), "POSITION 2");
} else if (position == 3) {
Utils.showToast(getContext(), "POSITION 3");
}
}
});
}
My item it have colour white.
I want when :
I click at position == 0.
Text Color item of position == 0 change to dark. and position different have colour white.
I click position == 1 :
Text colour item of position == 1 change to colour dark. And position different back colour white.
I click position == 2 :
Text colour of position == 2 change to Dark and position different back colour white.
I click position == 3 :
Text colour of position == 3 change to Dark and position different back colour white.
Please. Help me!
1- Create variable currentPosition default = -1 in adapter
private int currentPosition =-1;
2- onBindViewHolder set default text color Black and when user click view:
notifyItemChanged(currentPosition) - update default view for old view(reload)
Set text color White.
#Override
public void onBindViewHolder(final DataObjectHolder holder, final int position) {
ViewGroup.LayoutParams layoutParams = holder.view.getLayoutParams();
holder.view.setLayoutParams(layoutParams);
final String text = mDataSet.get(position);
holder.textView.setTextColor(Color.BLACK);
holder.textView.setText(text);
holder.view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(currentPosition>=0) {
notifyItemChanged(currentPosition);
}
holder.textView.setTextColor(Color.WHITE);
currentPosition=position;
}
});
}
I'm not sure I understand fully what you are trying to achieve but if you are trying to change the colour of your TextField's text and assuming your OnItemClickListener is being called:
Create a field that will hold all of your TextViews.
private TextView[] textViews;
In your onCreateView method.
textViews = new TextView[4];
textViews[0] = (TextView) view.findViewById(R.id.textViewOne);
textViews[1] = (TextView) view.findViewById(R.id.textViewTwo);
textViews[2] = (TextView) view.findViewById(R.id.textViewThree);
textViews[3] = (TextView) view.findViewById(R.id.textViewFour);
Now in your OnItemClickListener
#Override
public void onResume() {
super.onResume();
((CategoryAdapter) adapter).setOnItemClickListener(
new CategoryAdapter.MyClickListener() {
#Override
public void onItemClick(int position, View v) {
Color white = getResources().getColor( R.color.color_text_white );
Color dark = getResources().getColor( R.color.color_text_dark );
for ( int i = 0; i < textViews.length; i++ ) {
TextView textView = textViews[i];
if ( i == position )
textView.setTextColor( dark );
else
textView.setTextColor( white );
}
}
});
}
class ColorAdapter extends RecyclerView.Adapter<ColorSizeViewHolder> {
Context context;
ArrayList<ColorContents> colorContents;
int current_position=-1;
int previous_position=-1;
public ColorAdapter(Context context, ArrayList<ColorContents> colorContents) {
this.context = context;
this.colorContents = colorContents;
}
#NonNull
#Override
public ColorSizeViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v= LayoutInflater.from(context).inflate(R.layout.color_size_model,parent,false);
return new ColorSizeViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull final ColorSizeViewHolder holder, final int position) {
holder.color_size.setText(colorContents.get(position).getColor());
holder.color_size.setTextColor(context.getResources().getColor(R.color.colorAccent));
holder.color_size.setTag(position);
holder.color_size.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int pos = (int)v.getTag();
holder.color_size.setTextColor(context.getResources().getColor(R.color.colorPrimary));
current_position=pos;
if (previous_position!=-1 && current_position!=previous_position)
{
notifyItemChanged(previous_position);
}
previous_position=pos;
}
});
holder.setItemClickListner(new ItemClickListner() {
#Override
public void onItemClick(int pos) {
}
});
}
#Override
public int getItemCount() {
return colorContents.size();
}
}

Categories

Resources