i have a program in which i have multiple questions and 2 options (radiobuttons) when i check 1 and scroll listview it gets unchecked. i will post the whole code kindly fix it for me. I think its something wrong with adapter class
MainActivity
public class MainActivity extends AppCompatActivity {
ListView simpleList;
String[] questions;
Button submit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get the string array from string.xml file
questions = getResources().getStringArray(R.array.questions);
// get the reference of ListView and Button
simpleList = (ListView) findViewById(R.id.simpleListView);
submit = (Button) findViewById(R.id.submit);
// set the adapter to fill the data in the ListView
CustomAdapter customAdapter = new CustomAdapter(getApplicationContext(), questions);
simpleList.setAdapter(customAdapter);
// perform setOnClickListerner event on Button
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String message = "";
// get the value of selected answers from custom adapter
for (int i = 0; i < CustomAdapter.selectedAnswers.size(); i++) {
message = message + "\n" + (i + 1) + " " + CustomAdapter.selectedAnswers.get(i);
}
// display the message on screen with the help of Toast.
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
}
});
}
Custom Adapter
public class Questions_Adapter extends BaseAdapter {
Activity context;
String[] questionsList;
String age_range;
LayoutInflater inflter;
public static ArrayList<Integer> selectedAnswers;
public Questions_Adapter(Activity applicationContext, String[] questionsList, String age_range) {
context = applicationContext;
this.questionsList = questionsList;
this.age_range = age_range;
// initialize arraylist and add string for all the questions
selectedAnswers = new ArrayList<>();
for (int i = 0; i < questionsList.length; i++) {
selectedAnswers.add(0);
}
inflter = (LayoutInflater.from(applicationContext));
}
#Override
public int getCount() {
return questionsList.length;
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
private class Viewholder{
TextView question;
RadioButton op1, op2, op3, op4, op5, op6;
}
#Override
public View getView(final int position, View view, ViewGroup viewGroup) {
Viewholder viewholder;
LayoutInflater inflater = context.getLayoutInflater();
if (view == null){
viewholder = new Viewholder();
view = inflater.inflate(R.layout.list_items,null);
viewholder.question = (TextView) view.findViewById(R.id.question);
viewholder.op1 = (RadioButton) view.findViewById(R.id.yes);
viewholder.op2 = (RadioButton) view.findViewById(R.id.no);
viewholder.op3 = (RadioButton) view.findViewById(R.id.op);
viewholder.op4 = (RadioButton) view.findViewById(R.id.op4);
viewholder.op5 = (RadioButton) view.findViewById(R.id.op5);
viewholder.op6 = (RadioButton) view.findViewById(R.id.op6);
view.setTag(viewholder);
}
else {
viewholder = (Viewholder) view.getTag();
}
// perform setOnCheckedChangeListener event on yes button
viewholder.op1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// set Yes values in ArrayList if RadioButton is checked
if (isChecked)
selectedAnswers.set(position, 1);
}
});
viewholder.op2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked)
selectedAnswers.set(position, 2);
}
});
viewholder.op3.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked)
selectedAnswers.set(position, 3);
}
});
viewholder.op4.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked)
selectedAnswers.set(position, 4);
}
});
viewholder.op5.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked)
selectedAnswers.set(position, 10);
}
});
viewholder.op6.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked)
selectedAnswers.set(position, 0);
}
});
// set the value in TextView
viewholder.op1.setText("None or Little of a time");
viewholder.op2.setText("Some of the time");
viewholder.op3.setText("A good part of the time");
viewholder.op4.setText("Most or All of the time");
viewholder.op5.setText("Yes");
viewholder.op6.setText("No");
viewholder.question.setText(questionsList[position]);
if(age_range.equals("ZSDS")){
viewholder.op5.setVisibility(View.GONE);
viewholder.op6.setVisibility(View.GONE);
}
if(age_range.equals("GDS")){
viewholder.op1.setVisibility(View.GONE);
viewholder.op2.setVisibility(View.GONE);
viewholder.op3.setVisibility(View.GONE);
viewholder.op4.setVisibility(View.GONE);
}
return view;
}
}
First of all you need to save the tick(checkbox selection) in your model, say isSelected = true & call notifyDataSetChanged. and then inside getView() method u need to check for this flag and set checkbox state based on that.
basically your view is regenerate after every scroll because you are not checking whether view is null or not.
You have to check first view and use holder instead of creating new object of widget every time . here is solution hope , it will work with your listview.
public class CustomAdapter extends BaseAdapter {
static class ViewHolder {
TextView question ;
RadioButton yes,no;
}
Context context;
String[] questionsList;
LayoutInflater inflter;
public static List<String> selectedAnswers;
public CustomAdapter(Context applicationContext, String[] questionsList) {
context = applicationContext;
this.questionsList = questionsList;
// initialize arraylist and add static string for all the questions
selectedAnswers = new ArrayList<>();
for (int i = 0; i < questionsList.length; i++) {
selectedAnswers.add("Not Attempted");
}
inflter = (LayoutInflater.from(applicationContext));
}
#Override
public int getCount() {
return questionsList.length;
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(final int i, View view, ViewGroup viewGroup) {
ViewHolder holder = new ViewHolder();
if(view==null){
view = inflter.inflate(R.layout.list_items, null);
// get the reference of TextView and Button's
holder.question = (TextView) view.findViewById(R.id.question);
holder.yes = (RadioButton) view.findViewById(R.id.yes);
holder.no = (RadioButton) view.findViewById(R.id.no);
// perform setOnCheckedChangeListener event on yes button
view.setTag(holder);
}else{
holder = (ViewHolder) view.getTag();
}
holder.yes.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// set Yes values in ArrayList if RadioButton is checked
if (isChecked)
selectedAnswers.set(i, "Yes");
}
});
// perform setOnCheckedChangeListener event on no button
holder.no.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// set No values in ArrayList if RadioButton is checked
if (isChecked)
selectedAnswers.set(i, "No");
}
});
// set the value in TextView
question.setText(questionsList[i]);
return view;
}
}
When you scroll the view is recycled for displaying the items so the selection of the other old list item that went out of view is coming for the wrong items. So you need to reset the selection for Radio Button when the get view is called.
So you can add the following code in the getVeiw() Method for the selection to work properly
if(position < selectedAnswers.size() && selectedAnswers.get(position) != null) {
switch(selectedAnswers.get(position)) {
case 1:
viewholder.op1.setChecked(true);
break;
case 2:
viewholder.op2.setChecked(true);
break;
case 3:
viewholder.op3.setChecked(true);
break;
case 4:
viewholder.op4.setChecked(true);
break;
case 10:
viewholder.op5.setChecked(true);
break;
case 0:
viewholder.op6.setChecked(true);
break;
default:
viewholder.op1.setChecked(false);
viewholder.op2.setChecked(false);
viewholder.op3.setChecked(false);
viewholder.op4.setChecked(false);
viewholder.op5.setChecked(false);
viewholder.op6.setChecked(false);
}
}
This will set your selection of the radio button on scroll of the listview.
Related
I am new to android. I am having trouble with recyclerview with check boxes.
I am using a recycler view that has check boxes. Now the titles with checked check boxes should appear in my activity. I have added the check box selected title in the array list how do I get them in the activity?
I just need the checked check boxes array list in my activity.
below is my adapter class
public class CheckboxAdapter extends
RecyclerView.Adapter<CheckboxAdapter.ViewHolder> {
private List<SearchListItem> searchListItems;
private OnSearchItemSelected onSearchItemSelected;
public ArrayList<String> addTitle;
CheckboxAdapter(List<SearchListItem> arrayList, OnSearchItemSelected onSearchItemSelected) {
this.searchListItems = arrayList;
this.onSearchItemSelected = onSearchItemSelected;
}
class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
#BindView(R.id.title)
TextView mTxtTitle;
#BindView(R.id.checkBox)
CheckBox checkBox;
ViewHolder(View row) {
super(row);
ButterKnife.bind(this, row);
row.setOnClickListener(this);
}
#Override
public void onClick(View view) {
int pos = getAdapterPosition();
SearchListItem searchListItem = searchListItems.get(pos);
try {
onSearchItemSelected.onClick(pos, searchListItem);
} catch (Exception e) {
e.printStackTrace();
}
}
}
#Override
public int getItemCount() {
// TODO Auto-generated method stub
return searchListItems.size();
}
#Override
public void onBindViewHolder(#NonNull final CheckboxAdapter.ViewHolder holder, final int position) {
SearchListItem output = searchListItems.get(position);
holder.mTxtTitle.setText(output.title);
holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
addAllTitle(holder);
}
}
});
}
public OnSearchItemSelected getOnSearchItemSelected() {
return onSearchItemSelected;
}
public void addAllTitle(ViewHolder holder) {
for (int i = 0; i < addTitle.size(); i++) {
addTitle.add(String.valueOf(holder.mTxtTitle));
}
}
#NonNull
#Override
public CheckboxAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int arg1) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
View contactView = inflater.inflate(R.layout.adapter_checkbox, parent, false);
return new CheckboxAdapter.ViewHolder(contactView);
}
}
you have to add one boolean in your model class such as isChecked
make it true if checkBox is checked else false
get same list which is passed in activity to adapter, this list will give you all checked boxes
for ex
in activity
adapter = new MyAdapter(myList);
/*you can get all checked boxes here, paste this code where you need it*/
for(i=0; i<myList.size();i++){
if(myList.isChecked()){
//... do somehing ...
}
}
in adapter
onBindViewHolder() method
holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
myList.setchecked(isChecked);
}
});
I have a listview whereby each listviewitem has a checkbox that the user can select an item with. I also have a checkbox above the listviewwhich is expected to automatically check all the checkboxes in my list when clicked.
I am having problems implementing the appropriate for this. Any ideas?
public class NotesActivity extends AppCompatActivity {
private CheckBox universalCheckBox;
private ListView mListNotes;
NoteListAdapter na;
private boolean isAnyItemChecked = false;
private CheckBox mCheckBox;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notes);
mListNotes = findViewById(R.id.main_listview);
// handling long click for list view item
mListNotes.setLongClickable(true);
mListNotes.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
for (int index = 0; index < parent.getChildCount(); ++index) {
View nextChild = (parent.getChildAt(index));
mCheckBox = nextChild.findViewById(R.id.checkbox);
mCheckBox.setVisibility(View.VISIBLE);
universalCheckBox.setVisibility(View.VISIBLE);
}
CheckBox checkBox = view.findViewById(R.id.checkbox);
checkBox.setChecked(true);
isAnyItemChecked = true;
return true;
}
});
universalCheckBoxLogic();
}
private void universalCheckBoxLogic() {
universalCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
mCheckBox.setChecked(true); // this not working for me
}
});
}
}
universalCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
checkAll(isChecked);
}
}
);
private void checkAll(boolean checked){
for (int index = 0; index < parent.getChildCount(); ++index) {
View nextChild = (listView.getChildAt(index));
mCheckBox = nextChild.findViewById(R.id.checkbox);
mCheckBox.setVisibility(View.VISIBLE);
mCheckBox.setChecked(checked);
}
}
I'm trying to retrieve all the checkboxes from my RecyclerView in order to uncheck them. However, this error is shown. Below are the classes that LogCat points to.
java.lang.IllegalArgumentException: itemView may not be null
at android.support.v7.widget.RecyclerView$ViewHolder.<init>(RecyclerView.java:10314)
at br.com.ufrn.marceloaugusto.tasklist.adapter.ProdutoAdapter$ProdutosViewHolder.<init>(ProdutoAdapter.java:0)
at br.com.ufrn.marceloaugusto.tasklist.MainActivity.onOptionsItemSelected(MainActivity.java:93)
MainActivity.java
public class MainActivity extends BaseActivity {
//private SQLiteDatabase banco;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setUpToolbar();
if (savedInstanceState == null) {
FragmentProdutos frag = new FragmentProdutos();
getSupportFragmentManager().beginTransaction().add(R.id.container, frag).commit();
}
//FAB
findViewById(R.id.fab).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
snack(view, "Adicionar produto");
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.action_desmarkAll) {
RecyclerView recycler = (RecyclerView) findViewById(R.id.recyclerView);
ProdutoAdapter.ProdutosViewHolder holder = null;
int id = 0;
for (int i = 0; i < recycler.getAdapter().getItemCount(); i++) {
holder = new ProdutoAdapter.ProdutosViewHolder(recycler.getChildAt(i)); **//Line 93**
if (holder.checkBox.isChecked()) {
holder.checkBox.setChecked(false);
}
}
return true;
}
return super.onOptionsItemSelected(item);
}}
ProdutoAdapter.java
public class ProdutoAdapter extends RecyclerView.Adapter<ProdutoAdapter.ProdutosViewHolder> {
private final Context context;
private final List<Produto> produtos;
//Interface para expor os eventos de toque na lista
private ProdutoOnClickListener produtoOnClickListener;
private ProdutoOnCheckListener produtoOnCheckListener;
public ProdutoAdapter(Context context, List<Produto> produtos, ProdutoOnClickListener produtoOnClickListener, ProdutoOnCheckListener produtoOnCheckListener) {
this.context = context;
this.produtos = produtos;
this.produtoOnClickListener = produtoOnClickListener;
this.produtoOnCheckListener = produtoOnCheckListener;
}
#Override
public int getItemCount() {
return this.produtos != null ? this.produtos.size() : 0;
}
#Override
public ProdutosViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.adapter_produto, parent, false);
ProdutosViewHolder holder = new ProdutosViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(final ProdutosViewHolder holder, final int position) {
Produto p = produtos.get(position);
holder.tNome.setText(p.getNome());
//holder.tPreco.setText(String.valueOf(p.getPreco()));
if (produtoOnClickListener != null) {
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
produtoOnClickListener.onClickProduto(view, position);
}
});
}
if (produtoOnCheckListener != null) {
holder.checkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
produtoOnCheckListener.onCheckProduto(view, position);
}
});
}
}
public interface ProdutoOnClickListener {
public void onClickProduto(View view, int idx);
}
public interface ProdutoOnCheckListener {
public void onCheckProduto(View view, int position);
}
public static class ProdutosViewHolder extends RecyclerView.ViewHolder {
public TextView tNome;
//public TextView tPreco;
CardView cardView;
public CheckBox checkBox;
public ProdutosViewHolder(View view) {
super(view);
tNome = (TextView) view.findViewById(R.id.nomeProduto);
//tPreco = (TextView) view.findViewById(R.id.precoProduto);
cardView = (CardView) view.findViewById(R.id.card_view);
checkBox = (CheckBox) view.findViewById(R.id.checkProduto);
}
}
}
Method getChildAt is method of ViewGroup, so recycler.getChildAt(i) will be null for you. In your case you should use produtos list, iterate over it and set its field associated to "checked" state to "false", invoke notifyDataSetChanged() method of your adapter and then onBindViewHolder() will automatically change holder's checkBox values.
So instead of
for (int i = 0; i < recycler.getAdapter().getItemCount(); i++) {
holder = new ProdutoAdapter.ProdutosViewHolder(recycler.getChildAt(i)); **//Line 93**
if (holder.checkBox.isChecked()) {
holder.checkBox.setChecked(false);
}
}
use this one:
for (Product product : produtos){
product.setChecked(false);
}
recycler.getAdapter().notifyDataSetChanged();
I supppose your class Project has such method.
In a RecyclerView the item views are recycled so you dont have as many itemviews as item in your List. Instead those itemviews are recycled and shows differents elements of your productos List.
Your problem is that you are in a for loop with the length of the List but inside you are using that index to access itemviews wich has not that much elements.
Instead, you should define a variable in Producto.class and update every time that check/uncheck the CheckBox of the item. And set this variable to false when you want to uncheck all and call
adapter.notifyDataSetChanged();
UPDATE:
ProdutoAdapter.java
Define a method to access list produtos and update onBindViewHolder like this:
if (produtoOnCheckListener != null) {
holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
produtos.get(position).setCheckBoxState(b);
produtoOnCheckListener.onCheckProduto(view, position);
}
});
}
MainActivity.class Define a ProductoAdapter variable and access to list productos to update the boolean value of each producto
[...]
ProductoAdapter productoAdapter = new ProductoAdapter();
[...]
for (int i = 0; i < productoAdapter.getItemCount(); i++) {
productoAdapter.getListProductos().get(i).setCheckBoxState(false);
}
productoAdapter.notifyDataSetChanged();
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?
I have a ListView in which a checkbox is displayed in each row.
Each and every time the checkbox is touched, I check wheteher it is checked or not.
But every time, the first item always return false. However, If if checked the 2nd item, the .ischecked() method of the checkbox of the first item alway return true.
Here is my code:
public class CustomSpecificCar extends ArrayAdapter<JSONObject>{
ListSpecificCars caller;
private JSONObject currentJson;
private CheckBox cbSelectedCar;
private int position;
public CustomSpecificCar(Context ctxt, List<JSONObject> list, ListSpecificCars caller){
super(ctxt, R.layout.custom_specific_car_row, list);
this.caller = caller;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(getContext());
View customView = inflater.inflate(R.layout.custom_specific_car_row, parent, false);
this.position = position;
// Set the reference of the layout
currentJson = getItem(this.position);
cbSelectedCar = (CheckBox)customView.findViewById(R.id.cbSelectedCar);
TextView tvBrand = (TextView)customView.findViewById(R.id.tvBrand);
TextView tvModel = (TextView)customView.findViewById(R.id.tvModel);
TextView tvOwnerEditable = (TextView)customView.findViewById(R.id.tvOwnerEditable);
TextView tvPriceEditable = (TextView)customView.findViewById(R.id.tvEstimatedPriceEditable);
try {
tvBrand.setText(currentJson.getString("brand"));
tvModel.setText(currentJson.getString("model"));
tvOwnerEditable.setText(currentJson.getString("owner"));
} catch (JSONException e) {
Log.e(e.getClass().getName(), "JSONException", e);
}
cbSelectedCar.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
if (cbSelectedCar.isChecked()){
caller.updateClickedUsername(currentJson, true); // Add to the List
Log.d("Added click ", "ok");
}
else if (!cbSelectedCar.isChecked()) {
caller.updateClickedUsername(currentJson, false); // Delete from the List
Log.d("Deleted click ", "nok");
}
}});
return customView;
}
}
What should I do to solve this issue?
Many thanks in advance!
You should use setOnCheckedChangeListener.
Sample:
checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
}
});
In your code:
cbSelectedCar.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked){
caller.updateClickedUsername(currentJson, true); // Add to the List
Log.d("Added click ", "ok");
}
else if (!isChecked) {
caller.updateClickedUsername(currentJson, false); // Delete from the List
Log.d("Deleted click ", "nok");
}
}
});
For using checked box as a Onclicklistener this will help you
CheckBox.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (((CheckBox) v).isChecked()) {
Toast.makeText(this, "CheckBox is checked", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "CheckBox is not checked", Toast.LENGTH_SHORT).show();
}
});