Check all checkboxes in a listview when one is clicked - java

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);
}
}

Related

How to display the Auto Scrolling RecyclerView position on TextView?

I am doing an app which auto-scrolls images, at the bottom of the screen there is a static layout, which I need to display the value of images that have already passed (i.e. position).
I get the correct value of images passed by implementing :
int position = holder.getAdapterPosition();
in the RecyclerViewListAdapter.java
now I need to display this value in the RecyclerViewListActivity.java
on a text view at the static layout beneath the Recycler view?
public class RecyclerViewListAdapter extends RecyclerView.Adapter {
Context context;
List<Data> dataList;
private SharedPreferences preferences;
public RecyclerViewListAdapter(Context context, List<Data> dataList) {
this.context = context;
this.dataList = dataList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_recycler_list, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
holder.mImage.setImageResource(dataList.get(position).getImage());
holder.mImage.setImageResource(dataList.get(position).getImage());
**int position = holder.getAdapterPosition();**
}
#Override
public int getItemCount() {
if (dataList == null || dataList.size() == 0)
return 0;
return dataList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView mNumberText,mText;
ImageView mImage;
LinearLayout mLinearLayout;
public MyViewHolder(View itemView) {
super(itemView);
mImage = (ImageView) itemView.findViewById(R.id.quran_page);
mLinearLayout = (LinearLayout) itemView.findViewById(R.id.linearLayout);
}
}
}
public class RecyclerViewListActivity extends AppCompatActivity {
RecyclerView mListRecyclerView;
ArrayList<Data> dataArrayList;
RecyclerViewListAdapter recyclerViewListAdapter ;
Runnable updater;
private boolean isTouch = false;
TextViewRemaining;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recycler_view_list);
final TextView TextViewRemaining = (TextView) findViewById(R.id.TextViewRemaining);
**TextViewRemaining.setText("Position: "+position);**
initializeView();
mListRecyclerView.addOnItemTouchListener(new RecyclerTouchListener(this,
mListRecyclerView, new ClickListener() {
#Override
public void onClick(View view, int position) {
}
#Override
public void onLongClick(View view, int position) {
Toast.makeText(RecyclerViewListActivity.this, "Long press on position :" + position,
Toast.LENGTH_LONG).show();
}
}));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
return super.onOptionsItemSelected(item);
}
public static interface ClickListener{
public void onClick(View view,int position);
public void onLongClick(View view,int position);
}
class RecyclerTouchListener implements RecyclerView.OnItemTouchListener{
private ClickListener clicklistener;
private GestureDetector gestureDetector;
//#RequiresApi(api = Build.VERSION_CODES.CUPCAKE)
public RecyclerTouchListener(Context context, final RecyclerView recycleView, final ClickListener clicklistener){
this.clicklistener=clicklistener;
gestureDetector=new GestureDetector(context,new GestureDetector.SimpleOnGestureListener(){
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View child=recycleView.findChildViewUnder(e.getX(),e.getY());
if(child!=null && clicklistener!=null){
clicklistener.onLongClick(child,recycleView.getChildAdapterPosition(child));
}
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child=rv.findChildViewUnder(e.getX(),e.getY());
if(child!=null && clicklistener!=null && gestureDetector.onTouchEvent(e)){
clicklistener.onClick(child,rv.getChildAdapterPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
private void initializeView()
{
mListRecyclerView = (RecyclerView) findViewById(R.id.vR_recyclerViewList);
setValues();
}
private void setValues(){
prepareData();
recyclerViewListAdapter = new RecyclerViewListAdapter(RecyclerViewListActivity.this,dataArrayList);
mListRecyclerView.setLayoutManager(new LinearLayoutManager(RecyclerViewListActivity.this)); // original
mListRecyclerView.setItemAnimator(new DefaultItemAnimator());
mListRecyclerView.setHasFixedSize(false);
mListRecyclerView.setAdapter(recyclerViewListAdapter);
recyclerViewListAdapter.notifyDataSetChanged();
final int speedScroll = 2000; //default is 2000 it need to be 30000
final Handler handler = new Handler();
final Runnable runnable = new Runnable() {
int count = 0;
// boolean flag = true;
#Override
public void run() {
boolean x=true;
// while(x) {
if (count < recyclerViewListAdapter.getItemCount()) {
if (count == recyclerViewListAdapter.getItemCount() - 1) {
flag = false;
} else if (count == 0) {
flag = true;
}
}
if (flag) count++;
// else count--;
mListRecyclerView.smoothScrollToPosition(count);
handler.postDelayed(this, speedScroll);
}
};
handler.postDelayed(runnable,speedScroll);
}
private void prepareData(){
dataArrayList = new ArrayList<>();
Data data1 = new Data();
data1.setImage(R.drawable.p1);
dataArrayList.add(data1);
Data data2 = new Data();
data2.setImage(R.drawable.p2);
dataArrayList.add(data2);
Data data3 = new Data();
data3.setImage(R.drawable.p3);
dataArrayList.add(data3);
Data data4 = new Data();
data4.setImage(R.drawable.p4);
dataArrayList.add(data4);
Data data5 = new Data();
data5.setImage(R.drawable.p5);
dataArrayList.add(data5);
}
}
So, How can I show the position value on textView in a real-time, as position is a dynamic value, I expect the output on the textView to change as the images passed to the top.
Many Thanks in advance.
This how I solve my problem:
I save the position value in a power Preference(an easier version of shared Preferences)-many thanks to:
Ali Asadi(https://android.jlelse.eu/powerpreference-a-simple-approach-to-store-data-in-android-a2dad4ddc4ac)
I use a Thread that updates the textview every second-many thanks to:
https://www.youtube.com/watch?v=6sBqeoioCHE&t=149s
Thanks for all.

Using Checkbox with recyclerview

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);
}
});

Radio Button gets uncked and automatically checked in listview scrolling

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.

ItemView may not be null

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();

Hide or Show checkboxes inside Custom grid adapter for all Positions

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?

Categories

Resources