How to get check box values from dynamically created checkbox - android

Here is the code for my check box.
if (type.equalsIgnoreCase("checkbox")){
String checkBoxText = dataObj.getString("checkboxname");
checkBox = dynamicviews.CreateCheckbox(context,value,checkBoxText);
id = R.id.gl + i + 9;
if (j == 2) {
j = 0;
tableRow = new TableRow(context);
tableRow.setPadding(0, 10, 0, 10);
tableLayout.addView(tableRow);
}
j++;
tableRow.addView(checkBox);
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
String string = checkBox.getText().toString();
Log.i("checkbox",string);
}
});
}
and below code is for creating checkbox
public CheckBox CreateCheckbox(Context context,String checkName,String checkBoxText){
checkBox = new CheckBox(context);
checkBox.setGravity(Gravity.CENTER);
checkBox.setTextAlignment(Gravity.CENTER);
checkBox.setText(checkBoxText);
checkBox.setTextColor(Color.WHITE);
checkBox.setBackgroundResource(R.drawable.custom_rdbtn);
checkBox.setButtonDrawable(new StateListDrawable());
checkBox.setCompoundDrawablePadding(10);
return checkBox;
}
and problem is am getting the value of last created checkbox for each one.

checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
String string = buttonView.getText().toString();
Log.i("checkbox",string);
}
});
i got the solution

You are adding the checkBoxobject to the tableRow BEFORE you set its setOnCheckedChangeListener - so it will only work for the last checkBox you've created.
To solve this, you simply need to do set the setOnCheckedChangeListener first, and then call the tableRow.addView(checkBox) - see the code below:
//first, set the setOnCheckedChangeListener on this checkBox,
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{ String string = buttonView.getText().toString();
Log.i("checkbox",string);
}
});
//only now do you add the view
tableRow.addView(checkBox);
Give it a try, I hope it helps.

Related

TableLayout not refreshing after findViewById

I am trying to render news articles based on a few toggle buttons in a fragment. The articles show up when the correct button (allButton) is clicked, but don't disappear. Here is my code:
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_dashboard, container, false);
ToggleButton allButton = (ToggleButton) root.findViewById(R.id.allButton);
ToggleButton readButton = (ToggleButton) root.findViewById(R.id.readButton);
ToggleButton unreadButton = (ToggleButton) root.findViewById(R.id.unreadButton);
//TableLayout table = (TableLayout) root.findViewById(R.id.newsTable);
//showArticles(root, table, allButton, readButton, unreadButton);
allButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
//buttonView.setBackgroundColor(Color.WHITE);
buttonView.setTextColor(Color.BLACK);
unreadButton.setChecked(false);
allButton.setChecked(true);
readButton.setChecked(false);
TableLayout table = (TableLayout) root.findViewById(R.id.newsTable);
showArticles(root, table, allButton, readButton, unreadButton);
} else {
//buttonView.setBackgroundColor(Color.BLACK);
buttonView.setTextColor(Color.WHITE);
}
}
});
readButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
//buttonView.setBackgroundColor(Color.WHITE);
buttonView.setTextColor(Color.BLACK);
allButton.setChecked(false);
readButton.setChecked(true);
unreadButton.setChecked(false);
TableLayout table = (TableLayout) root.findViewById(R.id.newsTable);
showArticles(root, table, allButton, readButton, unreadButton);
} else {
//buttonView.setBackgroundColor(Color.BLACK);
buttonView.setTextColor(Color.WHITE);
}
}
});
unreadButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
//buttonView.setBackgroundColor(Color.WHITE);
buttonView.setTextColor(Color.BLACK);
allButton.setChecked(false);
unreadButton.setChecked(true);
readButton.setChecked(false);
TableLayout table = (TableLayout) root.findViewById(R.id.newsTable);
showArticles(root, table, allButton, readButton, unreadButton);
} else {
//buttonView.setBackgroundColor(Color.BLACK);
buttonView.setTextColor(Color.WHITE);
}
}
});
return root;
Please note that the showArticles edits the TableLayout passed directly. I thought that each time I called root.findViewById(), that the TableLayout would refresh to only the XML layout (disregarding programmatic additions), but it seems to keep the new tablerows added. Any help would be greatly appreciated! Thanks!

How to fix Checkbox in RecyclerView when no solution works?

I'm trying to set up a checkbox in my recycler view, but I'm facing the common problem of random checks without my control. I check one item and some more random items are being checked at the same time.
I realise this is a common question here, but the solutions I found here don't seem to work. Among many others I was trying to follow different instructions in this thread:
Android RecyclerView checkbox checks itself
but what seems to be the problem is that functions isSelected and setSelected can't be resolved.
My best guess is that the reason for this complication might be that my onCheckedChange action is actually interfaced from the main activity, as you can see at the bottom of the code below. Is that what complicates the code (can't avoid it)?
public LocationRecyclerViewAdapter(List<IndividualLocation> styles,
Context context, ClickListener cardClickListener, OnCheckedChangeListener checkedChangeListener, int selectedTheme) {
this.context = context;
this.listOfLocations = styles;
this.selectedTheme = selectedTheme;
this.clickListener = cardClickListener;
this.onCheckedChangeListener = checkedChangeListener;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
int singleRvCardToUse = R.layout.single_location_map_view_rv_card;
View itemView = LayoutInflater.from(parent.getContext()).inflate(singleRvCardToUse, parent, false);
return new ViewHolder(itemView);
}
public interface ClickListener {
void onItemClick(int position);
}
public interface OnCheckedChangeListener {
void onCheckboxClick(int position);
}
#Override
public int getItemCount() {
return listOfLocations.size();
}
#Override
public void onBindViewHolder(final ViewHolder card, int position) {
final IndividualLocation locationCard = listOfLocations.get(position);
card.nameTextView.setText(locationCard.getName());
card.addressTextView.setText(locationCard.getAddress());
card.hoursTextView.setText(locationCard.getHours());
card.priceTextView.setText(locationCard.getPrice());
card.categoryTextView.setText(locationCard.getCategory());
card.cuisineTextView.setText(locationCard.getCuisine());
card.happyHourTextView.setText(locationCard.getHappyHour());
card.lunchDealTextView.setText(locationCard.getLunchDeal());
card.websiteTextView.setText("WEBSITE");
card.newPlaceTextView.setText(locationCard.getNewPlace());
card.websiteTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String url = locationCard.getWebsite();
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
context.startActivity(intent);
}
});
static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView nameTextView;
TextView addressTextView;
TextView priceTextView;
TextView hoursTextView;
TextView categoryTextView;
TextView cuisineTextView;
TextView happyHourTextView;
TextView lunchDealTextView;
TextView newPlaceTextView;
ConstraintLayout constraintUpperColorSection;
CardView cardView;
ImageView backgroundCircleImageView;
ImageView emojiImageView;
Button websiteTextView;
CheckBox checkBox;
ViewHolder(View itemView) {
super(itemView);
nameTextView = itemView.findViewById(R.id.location_name_tv);
addressTextView = itemView.findViewById(R.id.location_description_tv);
priceTextView = itemView.findViewById(R.id.location_price_tv);
hoursTextView = itemView.findViewById(R.id.location_hours_tv);
backgroundCircleImageView = itemView.findViewById(R.id.background_circle);
emojiImageView = itemView.findViewById(R.id.emoji);
constraintUpperColorSection = itemView.findViewById(R.id.constraint_upper_color);
categoryTextView = itemView.findViewById(R.id.location_type_tv);
cuisineTextView = itemView.findViewById(R.id.location_cuisine_tv);
happyHourTextView = itemView.findViewById(R.id.happyhour_tv);
lunchDealTextView = itemView.findViewById(R.id.lunchdeal_tv);
cardView = itemView.findViewById(R.id.map_view_location_card);
websiteTextView = itemView.findViewById(R.id.website);
newPlaceTextView = itemView.findViewById(R.id.new_place);
cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
clickListener.onItemClick(getLayoutPosition());
}
});
checkBox = itemView.findViewById(R.id.checkBox);
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
onCheckedChangeListener.onCheckboxClick(getLayoutPosition());
}
}});
}
#Override
public void onClick(View view) {
}
}
}
I'm sure there is some simple solution to this, but I've been cracking my head over this for way too long now. Thanks!
First of all, you have to check the checkbox programatically, for every item. Your model should hold the data, a simple boolean could do it.
The second is the trickiest one
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(buttonView.isPressed()){
if (isChecked ) {
onCheckedChangeListener.onCheckboxClick(holder.getAdapterPosition()());
}}
}});
You have to check if the checkbox is actually checked, in order to avoid confusions,
Inside your onBindViewHolder you have to set your checkbox either checked or unchecked. if true, your checkbox will be selected, else unselected,
because recycler view will be recycled every time you scroll, so you need to make sure you need to tell adapter that checkbox need to be checked or unchecked at that particular position.
why are you using getLayoutPosition() for getting checkbox position
use like this holder.getAdapterPosition()
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
onCheckedChangeListener.onCheckboxClick(holder.getAdapterPosition()());
}
}});
and move this listener to your onBindViewHolder()
Your data model should have a boolean variable isChecked. You can also give it an default value false. Now, in your adapter function onBindViewHolder, you should set value of your checkbox ex.
card.checkBox.setChecked(locationCard.getIsChecked())
Also, in your onCheckedChanged you should update your data
locationCard.setIsChecked(isChecked)
Now each time your RecyclerView Adapter reuses and list item, it will set the value of its checkbox correctly. Hope this helps.

Checkbox inside List View automatically checking and un-checking when scroll

I know that this question has been asked over and over again but still I haven't found/understand anything that I found. The checkbox is unchecked whenever the list is scrolled down or some of the checkbox is checked whenever the list is scrolled up.
Here is my code:
#Override
public View getView(final int position, View view, ViewGroup viewGroup) {
//View v = View.inflate(mContext, R.layout.sales_invoice_custom,null);
final ViewHolder holder;
if (view == null) {
view = View.inflate(mContext, R.layout.sales_invoice_custom, null);
holder = new ViewHolder();
holder.SelectInvoiceCB = (CheckBox) view.findViewById(R.id.selectInvoiceCB);
holder.SalesInvoiceNo = (TextView) view.findViewById(R.id.SINo);
holder.InvoiceDate = (TextView) view.findViewById(R.id.SIDate);
holder.InvoiceAmount = (TextView) view.findViewById(R.id.SIAmount);
holder.AmountDue = (TextView) view.findViewById(R.id.SIAmountDue);
holder.DueDate = (TextView) view.findViewById(R.id.SIdueDate);
holder.PayFull = (CheckBox) view.findViewById(R.id.SIFull);
holder.PayPartial = (CheckBox) view.findViewById(R.id.SIPartial);
holder.TotalAmount = (EditText) view.findViewById(R.id.SITotalAmount);
holder.CreditMemoID = (TextView) view.findViewById(R.id.creditMemoID);
holder.CreditMemoDate = (TextView) view.findViewById(R.id.creditMemoDate);
holder.CreditMemoReason = (TextView) view.findViewById(R.id.creditMemoReason);
holder.LL2 = (LinearLayout) view.findViewById(R.id.ll2);
holder.LL3 = (LinearLayout) view.findViewById(R.id.ll3);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
InvoicePopulate(holder,position);
return view;
}
public void InvoicePopulate(final ViewHolder holder, final int position) {
dbHelper = new DBHelper(mContext);
Calendar c = Calendar.getInstance();
SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd");
final String formattedDate = df1.format(c.getTime());
//holder.SelectInvoiceCB.setChecked(false);
holder.SalesInvoiceNo.setText(invoiceLists.get(position).getSales_Invoice_ID());
holder.InvoiceDate.setText(invoiceLists.get(position).getInvoice_Date());
holder.DueDate.setText(invoiceLists.get(position).getDue_Date());
float invAmount = 0;
invAmount = Math.round(Float.parseFloat(invoiceLists.get(position).getInvoice_Amount())*100.00)/(float)100.00;
holder.InvoiceAmount.setText(String.format("%,.2f",invAmount));
holder.AmountDue.setText(String.format("%,.2f",invAmount));
try {
if (invoiceLists.get(position).getAmount_Paid().toString().equals("") ||
invoiceLists.get(position).getAmount_Paid().toString().equals("0")) {
invAmount = 0;
invAmountDue = 0;
invAmountPaid = 0;
invAmount = Math.round(Float.parseFloat(invoiceLists.get(position).getInvoice_Amount())*100.00)/(float)100.00;
invAmountDue = invAmount - invAmountPaid;
Log.e("Without AmountPaid ", "Amount Due : " + String.valueOf(invAmountDue));
} else {
invAmount = 0;
invAmountDue = 0;
invAmountPaid = Math.round(Float.parseFloat(invoiceLists.get(position).getAmount_Paid())*100.00)/(float)100.00;
invAmount = Math.round(Float.parseFloat(invoiceLists.get(position).getInvoice_Amount())*100.00)/(float)100.00;
invAmountDue = invAmount - invAmountPaid;
Log.e("With AmountPaid ", "Amount Due : " + String.valueOf(invAmountDue));
}
final float finalInvAmount = invAmountDue;
holder.PayFull.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (holder.PayFull.isChecked()) {
holder.PayPartial.setChecked(false);
if (holder.SelectInvoiceCB.isChecked()) {
invoiceStatusValue = "PAID_FULL";
holder.TotalAmount.setText(String.valueOf(Math.round(finalInvAmount*100.00)/100.00));
//holder.TotalAmount.setText(holder.InvoiceAmount.getText().toString());
}
}
}
});
holder.PayPartial.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (holder.PayPartial.isChecked()) {
holder.PayFull.setChecked(false);
if (holder.SelectInvoiceCB.isChecked()) {
invoiceStatusValue = "PAID_PARTIAL";
holder.TotalAmount.setText("0.00");
}
}
}
});
holder.AmountDue.setText(String.format("%,.2f",invAmountDue));
} catch (Exception e) {
e.getMessage();
}
if (TotalPaymentAmount >= Float.parseFloat(String.valueOf(invAmountDue))) {
holder.SelectInvoiceCB.setChecked(true);
holder.PayFull.setChecked(true);
holder.PayFull.setClickable(true);
holder.PayPartial.setClickable(true);
holder.TotalAmount.setText(String.valueOf(Math.round(invAmountDue*100.00)/100.00));
}
}
} catch (Exception e){
e.getMessage();
System.out.println("Error - " + e);
} finally {
dbHelper.close();
}
}
You should store the checkbox is checked or not in your viewmodel class.Ex. boolean isChecked; than in getView() set the checkbox from viewmodel ischecked.
You have to manage checked state in model class. In your case you have to manage three booleans for PayFull, PayPartial and SelectInvoiceCB checkbox checked state.
When you done setChecked at that time update the model class checked behaviour like:
class YourModel{
public boolean isPayFull, isPayPartial, isSelectInvoice;
}
//This will update UI from model check behaviour
holder.PayFull.setChecked(invoiceLists.get(position).isPayFull);
holder.PayPartial.setChecked(invoiceLists.get(position).isPayPartial);
holder.SelectInvoiceCB.setChecked(invoiceLists.get(position).isSelectInvoice);
holder.PayFull.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (holder.PayFull.isChecked()) {
holder.PayPartial.setChecked(false);
if (holder.SelectInvoiceCB.isChecked()) {
invoiceStatusValue = "PAID_FULL";
}
}
//This is to manage the state of checkbox in model
invoiceLists.get(position).isPayFull = holder.PayFull.isChecked();
invoiceLists.get(position).isPayPartial= holder.PayPartial.isChecked();
invoiceLists.get(position).isSelectInvoice= holder.SelectInvoiceCB.isChecked();
}
});
holder.PayPartial.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (holder.PayPartial.isChecked()) {
holder.PayFull.setChecked(false);
if (holder.SelectInvoiceCB.isChecked()) {
invoiceStatusValue = "PAID_PARTIAL";
holder.TotalAmount.setText("0.00");
}
}
//This is to manage the state of checkbox in model
invoiceLists.get(position).isPayFull = holder.PayFull.isChecked();
invoiceLists.get(position).isPayPartial= holder.PayPartial.isChecked();
invoiceLists.get(position).isSelectInvoice= holder.SelectInvoiceCB.isChecked();
}
});
Generally, I prefer to do click events on checkbox rather than checked change listeners in list item, checked change will get call on scroll and update the UI on every scroll so better to appy click event on checkbox and manage checked state from model class as I mentioned you.
In Answer to your Question , the reason it's checking and unchecking lies in this piece of your code in all the CheckChangedListeners
if (holder.PayFull.isChecked()) {
holder.PayPartial.setChecked(false);
You are unchecking the check box as soon as its checked.
On a separate note you need to handle the checked states during view recycling.
Other wise the check boxes will not maintain the proper states. when scrolling.
One choice is to save the states in the ArrayList along with your data. Keep 3 boolean variables state1,state2,state3 for the check boxes.
In the InvoicePopulate(...) method -
holder.PayFull.setChecked(invoiceLists.get(position).getState1())
In the check changed listener add following line
invoicelists.get(position).setState1(isChecked)

Check which checkbox is checked/Unchecked in android

I am creating checkboxes at runtime but i don't know how to find that which checkbox is checked and which is unchecked?This is the code.
for (String s : options)
{
chk = new CheckBox(this);
System.out.println(s);
chk.setId(i++);
chk.setText(s);
selected=s;
chk.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (((CheckBox) v).isChecked())
DisplayToast(selected);
else
DisplayToast(selected);
}
});
lm.addView(chk);
}
You can get the id of CheckBox using getId() method ..
CheckBox checkBox = ((CheckBox) v);
if (checkBox.isChecked())
{
int checkBoxId = checkBox.getId(); // It will give you checked checkbox id..
DisplayToast(selected);
}
else
DisplayToast(selected);
Update:
To get all CheckBox states you have to iterate thru ChildViews of lm layout.
Something like,
for (int i = 0; i < lm.getChildCount(); i++) {
View v = lm.getChildAt(i);
if (v instanceof CheckBox) {
if (((CheckBox) v).isChecked())
// Check Checkbox
else
// Unchecked Checkbox
}
}
Note: I would suggest you can use onCheckedChangeListener instead of View.OnClickListener() to check - uncheck event of CheckBox. (But it is optional, it also works with OnClickListener)
You should use onCheckedChangeListener to define whether your checkbox checked:
chk.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
//checked
} else {
//not checked
}
}
});

checkbox can't create dynamically

Can Anybody help me? checkbox can't create dynamically . Just like sometimes I use the program create 6 checkboxes. Sometimes I create 8 checkboxes. I want to set each checkbox a event to catch the time when it's checked.In the following way, I get an error:Cannot refer to a non-final variable i inside an inner class defined in a different method.Change modifier of "i" to final.
The mCheckTime is a long array.
for(int i=0;i<optionsNum;i++){
mCheckBox[i]=new CheckBox(this);
mCheckBox[i].setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener(){
public void onCheckedChanged(CompoundButton buttonView, boolean isCheck){
if (mCheckBox[i].isChecked()) {
mCheckTime[i] = System.currentTimeMillis();
}
}
};
if your content view is LinearLayout, try
final CheckBox mCheckBox = new CheckBox(this);
mCheckBox
.setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView,
boolean isCheck) {
if (mCheckBox.isChecked()) {
mCheckBox.setText(System.currentTimeMillis() + "");
}
}
});
LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
addContentView(mCheckBox, params);
======EDIT======
or try this
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
setContentView(layout);
CheckBox[] mCheckBox = new CheckBox[6];
for (int i = 0; i < 6; i++) {
mCheckBox[i] = new CheckBox(this);
mCheckBox[i].setText(i + "");
mCheckBox[i]
.setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView,
boolean isCheck) {
if (isCheck) {
Toast.makeText(MainActivity.this,
System.currentTimeMillis() + "",
Toast.LENGTH_SHORT).show();
}
}
});
layout.addView(mCheckBox[i]);
}
Thank you very much. I use a final variable j to replace i inside the inner class.
for(int i=0;i<optionsNum;i++){
final int j = i;
mCheckBox[i]=new CheckBox(this);
mCheckBox[i].setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener(){
public void onCheckedChanged(CompoundButton buttonView, boolean isCheck){
if (mCheckBox[i].isChecked()) {
mCheckTime[i] = System.currentTimeMillis();
}
}
};

Categories

Resources