I have a ListView with many items. Each item has a button and when I click on it, it becomes invisible and another button becomes visible.
The issue is: when I scroll the ListView, many other items buttons are invisible. How can I fix it?
public class homebuyer_fruits_adapter extends BaseAdapter {
private ArrayList<Itemssetget> listData;
private LayoutInflater layoutInflater;
public static int cout=0;
List position_item=new ArrayList();
Context context;
String check;
int lastpostition=-1;
public static List<cartitemslist> cartlist=new ArrayList<>();
public homebuyer_fruits_adapter(Context aContext, ArrayList<Itemssetget> listData,String number) {
this.listData = listData;
layoutInflater = LayoutInflater.from(aContext);
context=aContext;
check=number;
this.notifyDataSetChanged();
}
public int getCount() {
return listData.size();
}
#Override
public Object getItem(int position) {
return listData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View v, ViewGroup parent) {
final ViewHolder holder;
final cartitemslist homeitemslist = new cartitemslist();
if (v == null) {
v = layoutInflater.inflate(R.layout.food_vegitablews_view, null);
holder = new ViewHolder();
holder.name = (TextView) v.findViewById(R.id.name_item);
holder.price = (TextView) v.findViewById(R.id.price_item);
holder.add_q = (ImageView) v.findViewById(R.id.add_quantity);
holder.delete_q = (ImageView) v.findViewById(R.id.delete_quantity);
holder.quantity = (TextView) v.findViewById(R.id.add_quantity_items);
//holder.description = (TextView) v.findViewById(R.id.description_item);
//holder.id = (TextView) v.findViewById(R.id.);
holder.imageView = (ImageView) v.findViewById(R.id.image_items);
holder.discount = (TextView) v.findViewById(R.id.discout_price);
holder.add = (Button) v.findViewById(R.id.addto_cart);
holder.units=(TextView)v.findViewById(R.id.item_units);
holder.percentage=(TextView)v.findViewById(R.id.discount_percentage);
holder.linearLayou=(LinearLayout)v.findViewById(R.id.Quantity_control_linnear_view) ;
holder.phone=check;
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
this.notifyDataSetChanged();
}
int i=Integer.parseInt(listData.get(position).getPrice())-Integer.parseInt(listData.get(position).getDiscountprice());
int d=i*100;
if((d/Integer.parseInt(listData.get(position).getPrice()))==0)
{
holder.percentage.setVisibility(View.GONE);
}
holder.percentage.setText(""+d/Integer.parseInt(listData.get(position).getPrice())+"% OFF");
holder.name.setText(listData.get(position).getName());
holder.price.setText("Rs " + listData.get(position).getPrice());
if(listData.get(position).getPrice().equals(listData.get(position).getDiscountprice()))
{
holder.price.setVisibility(View.GONE);
}
holder.price.setPaintFlags(holder.price.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
holder.discount.setText("Rs " + listData.get(position).getDiscountprice());
Picasso.with(context).load(listData.get(position).getImageurl())
.fit().centerCrop().into(holder.imageView);
holder.units.setText(listData.get(position).getUnits());
holder.add_q.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Toast.makeText(context,listData.get(position).getName(),Toast.LENGTH_LONG).show();
if(H.containsKey(position))
{
holder.quantity.setText(""+(1+Integer.parseInt(holder.quantity.getText().toString())));
cartlist.get(H.get(position)).setQuantity(holder.quantity.getText().toString());
}
}
});
holder.delete_q.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(H.containsKey(position)) {
if(holder.quantity.getText().toString().equals("1"))
{
holder.add.setVisibility(View.VISIBLE);
holder.linearLayou.setVisibility(View.GONE);
int i=H.get(position);
cartlist.remove(i);
cout--;
Fruits.numberofitems.setText(cout + "");
}
else {
holder.quantity.setText("" + (Integer.parseInt(holder.quantity.getText().toString()) - 1));
cartlist.get(H.get(position)).setQuantity(holder.quantity.getText().toString());
}
}
}
});
holder.add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Toast.makeText(context,"Add to cart"+holder.name.getText(),Toast.LENGTH_SHORT).show();
holder.add.setVisibility(View.GONE);
holder.linearLayou.setVisibility(View.VISIBLE);
// check=listData.get(position).getPhonenumber_seller();
if(cartlist.isEmpty()) {
cout++;
homeitemslist.setName(holder.name.getText().toString());
homeitemslist.setPrice(holder.price.getText().toString());
homeitemslist.setDiscountp(holder.discount.getText().toString());
homeitemslist.setQuantity(holder.quantity.getText().toString());
homeitemslist.setPhone_id(holder.phone);
homeitemslist.setImage(listData.get(position).getImageurl());
if(Fruits.numberofitems!=null)
{
Fruits.numberofitems.setText(cout + "");
}
shop_items.numberofitems.setText(cout + "");
buyer_home.numberofitems.setText(cout + "");
cartlist.add(homeitemslist);
H.put(position,cartlist.indexOf(homeitemslist));
}
else {
if(check.equals(cartlist.get(0).getPhone_id()))
{
cout++;
cartitemslist homeitemslist = new cartitemslist();
homeitemslist.setName(holder.name.getText().toString());
homeitemslist.setPrice(holder.price.getText().toString());
homeitemslist.setDiscountp(holder.discount.getText().toString());
homeitemslist.setQuantity(holder.quantity.getText().toString());
homeitemslist.setPhone_id(holder.phone);
homeitemslist.setImage(listData.get(position).getImageurl());
if(Fruits.numberofitems!=null)
{
Fruits.numberofitems.setText(cout + "");
}
shop_items.numberofitems.setText(cout + "");
buyer_home.numberofitems.setText(cout + "");
cartlist.add(homeitemslist);
H.put(position,cartlist.indexOf(homeitemslist));
}
else
{
Toast.makeText(context,"Clear the Previous cart First than you can buy from this shop",Toast.LENGTH_LONG).show();
}
}
}
});
// holder.description.setText(listData.get(position).getDiscription());
// holder.id.setText(listData.get(position).getId());
//holder.imageView.setImageAlpha(R.drawable.banana);
setanimation(v,position);
return v;
}
static class ViewHolder {
LinearLayout linearLayou;
TextView name;
TextView price;
TextView discount;
ImageView add_q;
ImageView delete_q;
TextView quantity;
ImageView imageView;
TextView description;
TextView units;
TextView percentage;
String phone;
Button add;
}
public void setanimation(View viewanim,int position)
{
if(position>lastpostition)
{
ScaleAnimation animation=new ScaleAnimation(0.0f,1.0f,0.0f,1.0f,
Animation.RELATIVE_TO_SELF,0.5f,Animation.RELATIVE_TO_SELF,0.5f);
animation.setDuration(1500);
viewanim.setAnimation(animation);
lastpostition=position;
}
}
}
Here is my adapter code.
I tried many ways but still stuck on this issue.
You set the visibility only in the OnClickListener, but you need to set it in getView() too, because your views will get recycled (re-used for a different item) when you scroll.
So in getView() you have to restore the complete state of the view, including button visibility. Store all state information in your list items. Inside your getView() do something like this:
#Override
public View getView(final int position, View v, ViewGroup parent) {
...
// the view (v) could be recycled and showing a state from another item
// e.g. the add button is visible
final Itemssetget listItem = listData.get(position);
// so we have to restore the state of the view for listItem above
// e.g. update the button visibility
holder.add.setVisibility(listItem.isAddButtonVisible() ? View.VISIBLE : View.GONE);
holder.add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
...
holder.add.setVisibility(View.GONE);
// save the state of the button, so it can be restored later
listItem.setAddButtonVisible(true);
...
}
}
...
}
Add the necessary member variables and getter/setter functions in Itemssetget:
public class Itemssetget {
...
private boolean isAddButtonVisible = false;
public boolean isAddButtonVisible() {
return isAddButtonVisible;
}
public void setAddButtonVisible(boolean isVisible) {
this.isAddButtonVisible = isVisible;
}
...
}
PS: Your code looks terrible. Have a look at naming conventions.
Related
I built a simple quiz app with sqlite database
There is some quiz headers and into this quiz headers we have some questions that show by recycler view. All questions have one question title and 4 answers and one correct answer. user chooses the radio button answers and after that click on confirm button that is located as item at the bottom of recycler view.
I can catch the correct answer with a simple way and send it to the activity with an interface. But i want to show the correct and wrong answers with changing the radio buttons color but I can't create another method and change the view holder items because I can't access to the view holders outside of 'onBindViewHolder' method . I can handle this with another adapter . I mean I can create a fake adapter that just show answers . Is it a right way ?
This is my code. It's a little messy. Sorry about that
public class QuestionRecyclerAdapter extends RecyclerView.Adapter<QuestionRecyclerAdapter.ViewHolder> {
private Context context;
private List<QuestionHolder> questionHolders;
private OnQuestionAnswerSelect onQuestionAnswerSelect;
private OnConfirmButtonClicked onConfirmButtonClicked;
public QuestionRecyclerAdapter(Context context, List<QuestionHolder> questionHolders) {
this.context = context;
this.questionHolders = questionHolders;
}
public void setOnQuestionAnswerSelect(OnQuestionAnswerSelect onQuestionAnswerSelect) {
this.onQuestionAnswerSelect = onQuestionAnswerSelect;
}
public void setOnConfirmButtonClicked(OnConfirmButtonClicked onConfirmButtonClicked){
this.onConfirmButtonClicked = onConfirmButtonClicked;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemView;
if (viewType == R.layout.question_item)
itemView = LayoutInflater.from(context).inflate(R.layout.question_item, parent, false);
else
itemView = LayoutInflater.from(context).inflate(R.layout.question_recycler_confirm_button, parent, false);
return new ViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
if (position != questionHolders.size()) {
QuestionModel currentModel = questionHolders.get(position).getQuestionModel();
holder.txtQuestion.setText(currentModel.getTitle());
holder.rBtnAnswer1.setText(currentModel.getOption1());
holder.rBtnAnswer2.setText(currentModel.getOption2());
holder.rBtnAnswer3.setText(currentModel.getOption3());
holder.rBtnAnswer4.setText(currentModel.getOption4());
if (onQuestionAnswerSelect != null) {
holder.questionRadioGroup.setOnCheckedChangeListener((v, i) -> {
RadioButton rBtnSelected = holder.questionRadioGroup.findViewById(holder.questionRadioGroup.getCheckedRadioButtonId());
int selectedRadioIndex = holder.questionRadioGroup.indexOfChild(rBtnSelected) + 1;
if (selectedRadioIndex == questionHolders.get(position).getQuestionModel().getCorrectNumber()) {
onQuestionAnswerSelect.onAnswerSelected(questionHolders.get(position).get_id(), true);
} else {
onQuestionAnswerSelect.onAnswerSelected(questionHolders.get(position).get_id(), false);
}
});
}
}else {
holder.btnConfirm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (onConfirmButtonClicked != null)
onConfirmButtonClicked.onConfirmClicked();
}
});
}
}
#Override
public int getItemCount() {
return questionHolders.size() + 1;
}
#Override
public int getItemViewType(int position) {
return (position == questionHolders.size()) ? R.layout.question_recycler_confirm_button : R.layout.question_item;
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView txtQuestion;
public RadioGroup questionRadioGroup;
public RadioButton rBtnAnswer1;
public RadioButton rBtnAnswer2;
public RadioButton rBtnAnswer3;
public RadioButton rBtnAnswer4;
public Button btnConfirm;
public ViewHolder(#NonNull View itemView) {
super(itemView);
txtQuestion = itemView.findViewById(R.id.txtQuestion);
questionRadioGroup = itemView.findViewById(R.id.questionRadioGroup);
rBtnAnswer1 = itemView.findViewById(R.id.rBtnAnswer1);
rBtnAnswer2 = itemView.findViewById(R.id.rBtnAnswer2);
rBtnAnswer3 = itemView.findViewById(R.id.rBtnAnswer3);
rBtnAnswer4 = itemView.findViewById(R.id.rBtnAnswer4);
btnConfirm = itemView.findViewById(R.id.btnConfirm);
}
}
}
public class QuizActivity extends AppCompatActivity {
RecyclerView questionRecyclerView ;
QuestionRecyclerAdapter adapter ;
QuestionDatabaseHelper questionDatabaseHelper ;
Map<Integer,Boolean> answeredRecords = new HashMap<>();
int score ;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
questionRecyclerView = findViewById(R.id.questionRecyclerView);
questionDatabaseHelper = new QuestionDatabaseHelper(this);
int selectedId = getIntent().getIntExtra(Constants.SELECTED_ID,0);
score = 0 ;
List<QuestionHolder> questionHolders = questionDatabaseHelper.getAllQuestionHoldersById(selectedId);
adapter = new QuestionRecyclerAdapter(this,questionHolders);
questionRecyclerView.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false));
questionRecyclerView.setAdapter(adapter);
adapter.setOnQuestionAnswerSelect(new OnQuestionAnswerSelect() {
#Override
public void onAnswerSelected(int questionNumber, boolean isCorrect) {
answeredRecords.put(questionNumber,isCorrect);
}
});
adapter.setOnConfirmButtonClicked(new OnConfirmButtonClicked() {
#Override
public void onConfirmClicked() {
score = 0 ;
for(Map.Entry<Integer,Boolean> item : answeredRecords.entrySet()){
if (item.getValue())
score++;
}
Log.e("THE SCORE IS ", String.valueOf(score));
}
});
}
private void displayRecords(){
for(Map.Entry<Integer,Boolean> item : answeredRecords.entrySet()){
Log.e("AAA",item.getKey() + " : " + item.getValue());
}
}
}
Make a function in adapter and send holder to activity by calling that function.
first make viewholder named holder1.
ViewHolder holder1;
then at the onBindViewHolder method add this:
holder1 = holder;
public ViewHolder getHolder(){
return holder1;
}
now you can use it in your Activity like this:
adapter.getHolder.rBtnAnswer1.setBackgroundColor(Color.parseColor("#FFFFFF")); //this is a example.
Good day!
There is a code:
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
private LayoutInflater inflater;
private List<PojoClassPrc> prc;
Context context;
RecyclerViewAdapter(Context context, List<PojoClassPrc> procedures) {
this.prc = procedures;
this.inflater = LayoutInflater.from(context);
}
#Override
public RecyclerViewAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.list_item, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(RecyclerViewAdapter.ViewHolder holder, int position) {
PojoClassPrc procedures = prc.get(position);
holder.sName1.setText(procedures.getsText1());
holder.sName3.setText(procedures.getsText3());
holder.sName2.setText(procedures.getsText2());
holder.sName1.setTextColor(Color.parseColor("#010101"));
holder.sName2.setTextColor(Color.parseColor("#ACACAC"));
holder.sName3.setTextColor(Color.parseColor("#737373"));
}
#Override
public int getItemCount() {
return prc.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
final TextView sName1, sName2, sName3;
final CheckBox sName5;
final CardView sName4;
ViewHolder(View view) {
super(view);
sName1 = (TextView) view.findViewById(R.id.lblListItem);
sName5 = (CheckBox) view.findViewById(R.id.checkBox2);
sName3 = (TextView) view.findViewById(R.id.lblListItem3);
sName2 = (TextView) view.findViewById(R.id.lblListItem2);
sName4 = (CardView) view.findViewById(R.id.item_card);
final boolean[] clicked = {false};
SharedPreferences prefs = context.getSharedPreferences("myPrefs", Context.MODE_PRIVATE);
boolean cbSelect = prefs.getBoolean("sName", false);
if (cbSelect){
sName3.setTextColor(Color.parseColor("#178DFC"));
sName4.setCardBackgroundColor(Color.parseColor("#C9FDFE"));
} else {
sName3.setTextColor(Color.parseColor("#737373"));
sName4.setCardBackgroundColor(Color.WHITE);
}
sName4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(!clicked[0]) {
sName5.setChecked(true);
sName3.setTextColor(Color.parseColor("#178DFC"));
sName4.setCardBackgroundColor(Color.parseColor("#C9FDFE"));
clicked[0] = true;
savePrefs(true, "sName");
} else {
sName5.setChecked(false);
sName3.setTextColor(Color.parseColor("#737373"));
sName4.setCardBackgroundColor(Color.WHITE);
clicked[0] = false;
savePrefs(false, "sName");
}
}});
}
}
private void savePrefs(boolean value, String name) {
SharedPreferences.Editor editor = context.getSharedPreferences("myPrefs", Context.MODE_PRIVATE).edit();
editor.putBoolean(name, value);
editor.apply();
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
return position;
}
}
sName4 is CardView, the point is that I want to implement such a thing:
I clicked on the card, the color of the text changed and the checkbox was set, but in the second press it is necessary to make it as before, say the checkbox is removed, and the color turns white, I can’t realize it in any way with if else, I don’t catch up with what and how, tell me please!
Thank you in advance!!!
P.S. I have a lot of fragments, so I do everything in the adapter
You can use state of CheckBox by calling method isChecked()
Try this:
sName4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (sName3.isChecked()){
sName3.setChecked(false);
sName3.setTextColor(Color.parseColor("#17fc6b")); // set your color
}else{
sName3.setChecked(true);
sName3.setTextColor(Color.parseColor("#178DFC"));
}
}});
more about checkbox
I'm creating an app for ordering food, and I created a Dish class and a Dish array adapter.
Currently you can add quantity for a specific dish by clicking on the view.
However, I wish to have 2 buttons to add or sub the quantity.
How can I make the 2 buttons for each dish, without the need to write for each element its ows button code? is there a way to make an "add" and "sub" methods and that the listview will know on which view it was clicked and by that update its quantity?
public Dish(String dishName, int dishPrice, int Image, int quantity) {
mdishName = dishName;
mdishPrice = dishPrice;
mdishPic = Image;
mquantity = quantity;
}
public class DishAdapter extends ArrayAdapter<Dish> {
public DishAdapter(Activity context, ArrayList<Dish> dishes){
super(context, 0, dishes);
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View listItemView = convertView;
if(listItemView == null){
listItemView = LayoutInflater.from(getContext()).inflate(R.layout.list_layout, parent, false);
}
final Dish currenDish = getItem(position);
TextView dishName = (TextView) listItemView.findViewById(R.id.dishName);
dishName.setText(currenDish.getDishName());
TextView dishPrice = (TextView) listItemView.findViewById(R.id.dishPrice);
dishPrice.setText(String.valueOf(currenDish.getDishPrice()));
ImageView image = (ImageView) listItemView.findViewById(R.id.dishPic);
image.setImageResource(currenDish.getDishPic());
image.setVisibility(View.VISIBLE);
TextView quantity = (TextView) listItemView.findViewById(R.id.quantity);
quantity.setText(String.valueOf(currenDish.getQuantity()));
return listItemView;
}
public class DesertsActivity extends AppCompatActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.deserts_activity);
final ArrayList<Dish> dishes = new ArrayList<Dish>();
dishes.add(new Dish("Number Cake",180, R.drawable.cake_number, 0));
dishes.add(new Dish("Ear of Haman", 40, R.drawable.ozen_haman, 0));
dishes.add(new Dish("Alphachores", 35, R.drawable.alphachores, 0));
dishes.add(new Dish("Snow Cookies", 35, R.drawable.snow_cookies, 0));
DishAdapter adapter = new DishAdapter(this, dishes);
final ListView listView = (ListView) findViewById(R.id.deserts_list);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
dishes.set(position, new Dish(dishes.get(position).getDishName(),
dishes.get(position).getDishPrice(), dishes.get(position).getDishPic(),
dishes.get(position).getQuantity()+1));
TextView quantity = (TextView) view.findViewById(R.id.quantity);
quantity.setText(String.valueOf(dishes.get(position).getQuantity()));
}
});
}
}
You have to create a separate Adaptor Class and then apply button click listeners on the buttons. I am attaching the image for the reference.
and My product Adaptor Is
public class ProductAdaptor extends RecyclerView.Adapter<ProductAdaptor.ViewHolder> {
List<ProductsItem> productsItems;
Context context;
public ProductAdaptor(Context context, List<ProductsItem> productsItems)
{
this.context = context;
this.productsItems = productsItems;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(context).inflate(R.layout.single_product_design,viewGroup, false);
return new ProductAdaptor.ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder viewHolder, int i) {
final ProductsItem productsItem = productsItems.get(i);
viewHolder.productname.setText(productsItem.getProductName());
Glide.with(context).load(productsItem.getProductImageUrl()).into(viewHolder.productImage);
viewHolder.stock.setText(productsItem.getStock());
viewHolder.farmername.setText(productsItem.getFarmerName());
// add listener on single Item
viewHolder.btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "Clicked", Toast.LENGTH_LONG).show();
}
});
viewHolder.btnPlus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// apply code to increment the number
// first of all get the value form text counter and increment after that bind on the UI
}
});
viewHolder.btnMinus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// first of all get the value form text counter and decrement after that bind on the UI
}
});
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public int getItemCount() {
return productsItems.size();
}
public class ViewHolder extends RecyclerView.ViewHolder
{
TextView productname;
ImageView productImage;
TextView stock, farmername, specility,qty;
Button btnPlus, btnMinus;
LinearLayout btnAdd;
public ViewHolder(#NonNull View itemView)
{
super(itemView);
productname = itemView.findViewById(R.id.productname);
productImage = itemView.findViewById(R.id.productimage);
stock = itemView.findViewById(R.id.stcokValue);
farmername = itemView.findViewById(R.id.farmerName);
qty = itemView.findViewById(R.id.qty);
specility = itemView.findViewById(R.id.specility);
btnPlus = itemView.findViewById(R.id.plusbutton);
btnMinus = itemView.findViewById(R.id.minusbtn);
btnAdd = itemView.findViewById(R.id.add_button);
}
}
}
I have to hide all the checkboxes for every [Position] product until User click button. When ever user clicks button check boxes will be show to select items for delete. Only check box will appear to change not whole grid view.
public class CartAdapter extends BaseAdapter {
Context context;
ArrayList<ProductCount> productCounts;
private LayoutInflater inflater;
private ImageButton plusButton;
private ImageButton minusButton;
private CheckBox selectToDelete;
private onDeleteCartItem onDeleteCartItem = null;
public CartAdapter(Context context, ArrayList<ProductCount> productCounts, onDeleteCartItem selectChangeListener) {
this.context = context;
this.productCounts = productCounts;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.onDeleteCartItem = selectChangeListener;
}
#Override
public int getCount() {
if(productCounts!=null)
return productCounts.size();
return 0;
}
#Override
public Object getItem(int position) {
if(productCounts!=null && position >=0 && position<getCount())
return productCounts.get(position);
return null;
}
#Override
public long getItemId(int position) {
if(productCounts!=null && position >=0 && position<getCount()){
ProductCount temp = productCounts.get(position);
return productCounts.indexOf(temp);
}
return 0;
}
public class ProductsListHolder{
public ImageView cart_item_img;
public TextView cart_item_desc;
public TextView cart_item_count;
public TextView cart_item_price_tag;
public TextView cart_item_price;
public ImageButton cart_item_minus;
public ImageButton cart_item_plus;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
final ProductsListHolder productsListHolder;
if(view == null){
view = inflater.inflate(R.layout.cart_adapter, parent, false);
productsListHolder = new ProductsListHolder();
productsListHolder.cart_item_img = (ImageView) view.findViewById(R.id.cart_item_img);
productsListHolder.cart_item_desc = (TextView) view.findViewById(R.id.cart_item_desc);
productsListHolder.cart_item_count = (TextView) view.findViewById(R.id.cart_item_count);
productsListHolder.cart_item_price_tag = (TextView) view.findViewById(R.id.cart_item_price_tag);
productsListHolder.cart_item_price = (TextView) view.findViewById(R.id.cart_item_price);
plusButton = (ImageButton) view.findViewById(R.id.cart_item_plus);
minusButton = (ImageButton) view.findViewById(R.id.cart_item_minus);
selectToDelete = (CheckBox) view.findViewById(R.id.select_to_delete);
selectToDelete.setTag(position);
view.setTag(productsListHolder);
}
else{
productsListHolder = (ProductsListHolder) view.getTag();
}
final ProductCount cat = productCounts.get(position);
selectToDelete.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
if(onDeleteCartItem != null){
onDeleteCartItem.onSelectToDelete((Integer)buttonView.getTag(),isChecked);
}
}
}
});
minusButton.setOnClickListener(new View.OnClickListener() {
int itemcount = 0;
#Override
public void onClick(View v) {
itemcount = productCounts.get(position).getCount();
productCounts.get(position).setCount(itemcount-1);
setProduct(position,productsListHolder,cat);
}
});
plusButton.setOnClickListener(new View.OnClickListener() {
int itemcount = 0;
#Override
public void onClick(View v) {
itemcount = productCounts.get(position).getCount();
productCounts.get(position).setCount(itemcount+1);
setProduct(position,productsListHolder,cat);
}
});
setProduct(position,productsListHolder,cat);
return view;
}
private void setProduct(int position, final ProductsListHolder productsListHolder, ProductCount pCount) {
Picasso.with(context).load(pCount.products.getImageResours()).into(new Target(){
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
productsListHolder.cart_item_img.setBackground(new BitmapDrawable(context.getResources(), bitmap));
}
#Override
public void onBitmapFailed(final Drawable errorDrawable) {
}
#Override
public void onPrepareLoad(final Drawable placeHolderDrawable) {
}
});
productsListHolder.cart_item_desc.setText(pCount.getProducts().getDescription());
productsListHolder.cart_item_price_tag.setText((String.valueOf(pCount.getCount()).concat(" x Rs. ").concat(String.valueOf((pCount.products.getPrice())))));
productsListHolder.cart_item_price.setText("Rs. ".concat(String.valueOf(pCount.getCount()* pCount.products.getPrice())));
productsListHolder.cart_item_count.setText(String.valueOf(pCount.getCount()));
}
#Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
}
}
Just handling your checkBox in your adapter because you got the position then can hide/show, OnClickListener, OnCheckedChangeListener however you want.
Reference to my answer here: Is there a simple way to check all CheckBox items in custimize BaseAdapter in android?
My app has a RecyclerView/CardView of Tasks. Each card is populated by my adapter with getAllTasksForUser() in my TaskTableController class:
public List<Task> getAllTasksForUser() {
final String QUERY_ALL_RECORDS = "SELECT * FROM " + TaskEntry.TABLE_NAME;
List<Task> taskList = new ArrayList<>();
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(QUERY_ALL_RECORDS, null);
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
Task task = new Task();
int TaskId = cursor.getColumnIndex(TaskEntry.COLUMN_TASK_ID);
task.setId(cursor.getString(TaskId));
task.setTitle(cursor.getString(cursor.getColumnIndex(TaskEntry.COLUMN_TASK_TITLE)));
task.setDue(new DateTime(cursor.getString(cursor.getColumnIndex(TaskEntry.COLUMN_TASK_DUE))));
task.setNotes(cursor.getString(cursor.getColumnIndex(TaskEntry.COLUMN_TASK_NOTES)));
task.setStatus(cursor.getString(cursor.getColumnIndex(TaskEntry.COLUMN_TASK_STATUS)));
taskList.add(task);
}
} else {
cursor.close();
db.close();
return taskList;
}
cursor.close();
db.close();
return taskList;
}
which is used to populate a ListArray of Task objects in my Adapter.
public class TaskAdapter extends RecyclerView.Adapter<TaskAdapter.TaskViewHolder> {
private List<Task> taskList;
OnItemClickListener mItemClickListener;
public TaskAdapter(List<Task> taskList) {
this.taskList = taskList;
}
#Override
public int getItemCount() {
return taskList.size();
}
#Override
public void onBindViewHolder(TaskViewHolder taskViewHolder, int i) {
Task task = taskList.get(i);
taskViewHolder.mTitle.setText(task.getTitle());
taskViewHolder.mDue.setText(task.getDue().toString());
if (task.getStatus().equals("completed")) {
taskViewHolder.mStatus.setChecked(true);
} else taskViewHolder.mStatus.setChecked(false);
}
#Override
public TaskViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.from(viewGroup.getContext()).
inflate(R.layout.tasklist_layout, viewGroup, false);
return new TaskViewHolder(itemView);
}
public void SetOnItemClickListener(final OnItemClickListener mItemClickListener) {
this.mItemClickListener = mItemClickListener;
}
public interface OnItemClickListener {
void onItemClick(View view , int position);
}
And subsequently in my MainActivity with
taskAdapter = new TaskAdapter(new TaskTableController(getActivity()).getAllTasksForUser());
return rootView;
My question is, once one of these items is clicked, how can I retrieve the sqlite _ID or another unique identifier to used as an input for a more detailed query which is called in another Activity/fragment (i'm not sure which one). I've tried by adding in the MainActivity
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mRecyclerView.setAdapter(taskAdapter);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
mRecyclerView.setItemAnimator(new DefaultItemAnimator());
taskAdapter.SetOnItemClickListener(new TaskAdapter.OnItemClickListener() {
#Override
public void onItemClick(View v, int position) {
m_ID = (TextView) v.findViewById(R.id._task_id);
Intent detailIntent = new Intent(v.getContext(), DetailActivity.class);
detailIntent.putExtra("TASK_ID", m_ID.getText().toString());
startActivity(detailIntent);
}
});
}
In my TaskTableController class i've added another method
public Task getTaskByID(String Id) {
final String SINGLE_TASK_QUERY = "SELECT * FROM " + TaskEntry.TABLE_NAME +
" WHERE " + TaskEntry._ID + " = " + Id;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(SINGLE_TASK_QUERY, null);
Task task = new Task();
while (cursor.moveToNext()){
task.setId(cursor.getString(cursor.getColumnIndex(TaskEntry.COLUMN_TASK_ID)));
task.setTitle(cursor.getString(cursor.getColumnIndex(TaskEntry.COLUMN_TASK_TITLE)));
task.setDue(new DateTime(cursor.getString(cursor.getColumnIndex(TaskEntry.COLUMN_TASK_DUE))));
task.setNotes(cursor.getString(cursor.getColumnIndex(TaskEntry.COLUMN_TASK_NOTES)));
}
return task;
}
should I call getTaskByID() in my DetailActivity or my DetailFragment which is responsible for inflating the detailed view? And how do I pass the ID from the intent extra to the query method?
This is how I do it most times:
1.In the constructor of your adapter, add an parameter (OnClickListener interface) and save it as an attribute in your custom adapter class.
2.In your onCreateViewHolder method, add to your view this click listener (implemented, for instance, in your Activity o fragment).In your case:
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
listClickListener.onClick(v);
}
});
3.Implement this method, getting the position clicked from the RecyclerView getChildPosition.
#Override
public void onClick(View view) {
int itemPosition = recyclerView.getChildPosition(view);
//With the position you should be able to get the object you want to extract from your adapter.
}
I hope this would help man.
Right answer from Juan Aguilar Guisado and for example in RecycleviewAdapter
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Picasso.with(mContext).load(R.drawable.add2new).into(holder.image);
holder.text.setText(mDataSet.get(position));
holder.askprice.setText(mAskPrice.get(position));
holder.bidprice.setText(mBidPrice.get(position));
holder.profit.setText(mProfit.get(position));
holder.setClickListener(new FavoriteAdapter.ViewHolder.ClickListener() {
public void onClick(View v, int pos, boolean isLongClick) {
if (isLongClick) {
// View v at position pos is long-clicked.
String poslx = pos + "";
Toast.makeText(mContext, "longclick " + poslx, Toast.LENGTH_SHORT).show();
} else {
// View v at position pos is clicked.
String possx = pos + "";
Toast.makeText(mContext, "shortclick " + possx, Toast.LENGTH_SHORT).show();
//toggleSelection(pos);
}
}
});
}
and in ViewHolder
static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener {
public ImageView image;
public TextView text;
public TextView askprice;
public TextView bidprice;
public TextView profit;
private ClickListener clickListener;
public ViewHolder(View itemView) {
super(itemView);
image = (ImageView) itemView.findViewById(R.id.image);
text = (TextView) itemView.findViewById(R.id.text);
askprice = (TextView) itemView.findViewById(R.id.askprice);
bidprice = (TextView) itemView.findViewById(R.id.bidprice);
profit = (TextView) itemView.findViewById(R.id.profit);
// We set listeners to the whole item view, but we could also
// specify listeners for the title or the icon.
itemView.setOnClickListener(this);
itemView.setOnLongClickListener(this);
}
/* Interface for handling clicks - both normal and long ones. */
public interface ClickListener {
/**
* Called when the view is clicked.
*
* #param v view that is clicked
* #param position of the clicked item
* #param isLongClick true if long click, false otherwise
*/
public void onClick(View v, int position, boolean isLongClick);
}
/* Setter for listener. */
public void setClickListener(ClickListener clickListener) {
this.clickListener = clickListener;
}
#SuppressWarnings("deprecation")
#Override
public void onClick(View v) {
// If not long clicked, pass last variable as false.
clickListener.onClick(v, getPosition(), false);
}
#SuppressWarnings("deprecation")
#Override
public boolean onLongClick(View v) {
// If long clicked, passed last variable as true.
clickListener.onClick(v, getPosition(), true);
return true;
}
}
#Override
public TaskViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.from(viewGroup.getContext()).
inflate(R.layout.tasklist_layout, viewGroup, false);
TaskViewHolder viewHolder = new TaskViewHolder(itemView);
viewHolder.itemView.setClickable(true);
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (taskListCallbacks != null)
taskListCallbacks.onTaskClick(taskList.get(viewHolder.getAdapterPosition()), v, viewHolder.getAdapterPosition());
}
});
return viewHolder;
}
public void setTaskListCallbacks(TaskListCallbacks taskListCallbacks){
this.taskListCallbacks = taskListCallbacks;
}
public interface TaskListCallbacks{
void onTaskClick(Task task, View v, int position);
}