In my application I am adding RadioButton dynamically depending on requirement.
Below is the code :
RadioGroup rg = new RadioGroup(StartExamActivity.this);
View v = new View(StartExamActivity.this);
v.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 2));
v.setBackgroundColor(Color.parseColor("#3593D4"));
rg.setLayoutParams(new RadioGroup.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
rg.setOrientation(LinearLayout.VERTICAL);
for (int i = 0; i < list.size(); i++) {
rdbtn[i] = new RadioButton(StartExamActivity.this);
rdbtn[i].setLayoutParams(new RadioGroup.LayoutParams(RadioGroup.LayoutParams.MATCH_PARENT, RadioGroup.LayoutParams.WRAP_CONTENT, 1f));
rdbtn[i].setId(i);
rdbtn[i].setText(list.get(i));
final String value = rdbtn[i].getText().toString();
rdbtn[i].setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (value.equalsIgnoreCase(answer)) {
marks = marks + 2;
}
}
});
rg.addView(rdbtn[i]);
}
questionContainer.addView(rg);
Now I want to increase the value of marks by 2 only ones even when RadioButton is checked multiple times. For that I want to know whether RadioButton is checked or not.
How to do this??
Please Help!!
Simple thing,
Why don't you use OnClickListener instead of onCheckedChanged>
rdbtn[i].setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
if(isChecked) {
// Write your logic here...
}
});
Related
I have two check boxes in a alert dialog box. What I want is that if one of the checkbox is clicked then other checkbox gets unchecked automatically. Only one checkbox can be clicked at a time. I've searched the internet and tried multiple solutions but no solution is working.
find ids of your check boxs...
checkBoxOne= (CheckBox)findViewById(R.id.checkBox1);
checkBoxTwo= (CheckBox)findViewById(R.id.checkBox2);
checkBoxOne.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
Here you unchecked the other check boxes
checkBoxTwo.setChecked(false);
}
}
});
checkBoxTwo.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
Here you unchecked the other check boxes
checkBoxOne.setChecked(false);
}
}
});
If you really want to use a CheckBox you have to programmatically uncheck the other button:
private void createCustomDialogCheckBox() {
LinearLayout dialogLayout = new LinearLayout(this);
dialogLayout.setOrientation(LinearLayout.VERTICAL);
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(MainActivity.this);
final CheckBox checkBoxOption1 = new CheckBox(this);
final CheckBox checkBoxOption2 = new CheckBox(this);
checkBoxOption1.setText("Option 1");
checkBoxOption2.setText("Option 2");
checkBoxOption1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
CheckBox otherCheckBox = checkBoxOption2;
if(isChecked && otherCheckBox.isChecked()){
otherCheckBox.setChecked(!otherCheckBox.isChecked());
}
}
});
checkBoxOption2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
CheckBox otherCheckBox = checkBoxOption1;
if(isChecked && otherCheckBox.isChecked()){
otherCheckBox.setChecked(!otherCheckBox.isChecked());
}
}
});
dialogLayout.addView(checkBoxOption1);
dialogLayout.addView(checkBoxOption2);
dialogBuilder.setView(dialogLayout);
dialogBuilder.show();
}
A better solution is to use RadioButton with does all this automatically:
private void createCustomDialogRadioButton() {
LinearLayout dialogLayout = new LinearLayout(this);
dialogLayout.setOrientation(LinearLayout.VERTICAL);
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(MainActivity.this);
RadioButton radioButtonOption1 = new RadioButton(this);
RadioButton radioButtonOption2 = new RadioButton(this);
radioButtonOption1.setText("Option 1");
radioButtonOption2.setText("Option 2");
RadioGroup radioGroup = new RadioGroup(this);
// radio buttons must be on the same radio group
// so that other buttons will automatically be unchecked / unselected
radioGroup.addView(radioButtonOption1);
radioGroup.addView(radioButtonOption2);
dialogLayout.addView(radioGroup);
dialogBuilder.setView(dialogLayout);
dialogBuilder.show();
}
Sometimes when i want to select choices in radio buttons there is something wrong with radio buttons which i can select Two radios However sometimes is right as default way it must be worked.
Here two sample in my application :
Here's my Code :
span.replace(0,0,getText(R.string.ForeSingleChoice));
new DynamicViews().makeNormalContent(getApplicationContext(),span,linearLayout,16,16,16,16,16.0f);
span.clear();
radioGroup = new DynamicViews().makeRadioGroup(getApplicationContext(),linearLayout);
new DynamicViews().makeRadioButton(getApplicationContext(),radioGroup,getString(R.string.Choice_Q2Mathematicsop1_2),-1);
new DynamicViews().makeRadioButton(getApplicationContext(),radioGroup,getString(R.string.Choice_Q2Mathematicsop2_2),5);
new DynamicViews().makeRadioButton(getApplicationContext(),radioGroup,getString(R.string.Choice_Q2Mathematicsop3_2),-1);
new DynamicViews().makeRadioButton(getApplicationContext(),radioGroup,getString(R.string.Choice_Q2Mathematicsop4_2),-1);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (checkedId)
{
case 5: goToNextLevel= true ;
break;
default: goToNextLevel = false;
break;
}
}
});
DynamicViews makeRadioButton:
public RadioButton makeRadioButton(Context context, RadioGroup radioGroup, String text, int Id) {
RadioButton radioButton = new RadioButton(context);
LinearLayout.LayoutParams Params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
radioButton.setBackgroundResource(R.drawable.backgroundbetweenradios);
radioButton.setLayoutParams(Params);
radioButton.setPadding(dpToPx(8,context) , dpToPx(8,context) , dpToPx(8,context) , dpToPx(8,context));
radioButton.setId(Id);
radioButton.setText(text);
radioButton.setTextColor(Color.BLACK);
radioGroup.addView(radioButton);
return radioButton;
}
DynamicViews makeRadioGroup:
public RadioGroup makeRadioGroup(Context context, LinearLayout linearLayout) {
RadioGroup radioGroup = new RadioGroup(context);
LinearLayout.LayoutParams Params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
radioGroup.setLayoutParams(Params);
radioGroup.setOrientation(LinearLayout.VERTICAL);
CardView cardView = new CardView(context);
cardView.setCardBackgroundColor(Color.WHITE);
cardView.setCardElevation(8.0f);
Params.setMargins(dpToPx(16,context) , dpToPx(16,context) , dpToPx(16,context) , dpToPx(16,context));
cardView.setLayoutParams(Params);
cardView.addView(radioGroup);
linearLayout.addView(cardView);
return radioGroup;
}
My application is consists of a lot of radiobuttons ,This is the approach i've made these radio buttons , what's the problem ? is this a bug ?
Have you tried to give each radio button unique id?
new DynamicViews().makeRadioButton(getApplicationContext(),radioGroup,getString(R.string.Choice_Q2Mathematicsop1_2),1);
new DynamicViews().makeRadioButton(getApplicationContext(),radioGroup,getString(R.string.Choice_Q2Mathematicsop2_2),5);
new DynamicViews().makeRadioButton(getApplicationContext(),radioGroup,getString(R.string.Choice_Q2Mathematicsop3_2),2);
new DynamicViews().makeRadioButton(getApplicationContext(),radioGroup,getString(R.string.Choice_Q2Mathematicsop4_2),3);
add this on your onCreate()
CompoundButton.OnCheckedChangeListener listener = new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
rbtn1.setChecked(yesrbtn == buttonView);
rbtn2.setChecked(norbtn == buttonView);
....
}
}
};
rbtn1.setOnCheckedChangeListener(listener);
rbtn2.setOnCheckedChangeListener(listener);
what this does is making sure that radiobuttons are not allowed to have 2 or more selection
I have dynamic check boxes which are having values like
check box 1 = $ 20
check box 2 = $ 10
if i click one check box then the value should reflect in a text view and if i select two check boxes then the value should be added to that text view or deselect the check box the value should be subtracted from that text view.
This check box values are coming dynamically so i need to add/subtract those two values and show the total value in the text view.
How can i do that please help me.
Thanks in advance
Hear is Tested code for this and working fine..
try this
public class MainActivity extends Activity implements OnCheckedChangeListener {
CheckBox cb1, cb2;
TextView tv1;
int count = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cb1 = (CheckBox) findViewById(R.id.checkBox1);
cb2 = (CheckBox) findViewById(R.id.checkBox2);
tv1 = (TextView) findViewById(R.id.textView1);
cb1.setOnCheckedChangeListener(this);
cb2.setOnCheckedChangeListener(this);
}
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (buttonView.getId() == R.id.checkBox1) {
if (isChecked) {
count = count + Integer.parseInt(cb1.getText().toString());
} else {
if (count != 0) {
count = count - Integer.parseInt(cb1.getText().toString());
}
}
tv1.setText("" + count);
}
if (buttonView.getId() == R.id.checkBox2) {
if (isChecked) {
count = count + Integer.parseInt(cb2.getText().toString());
} else {
if (count != 0) {
count = count - Integer.parseInt(cb2.getText().toString());
}
}
tv1.setText("" + count);
}
}
}
Good Luck..
for check box we have one event listener as OnCheckedChangeListener
override this listener for both of your Checkboxes(e.g chkBox1, chkBox2), and
check
int value1,value2;
if(chkBox1.isChecked){
//store value of this checkbox into one variable i.e.
value1 = value of chkBox1;
}else{
// reset value for this chkBox1 i.e
value1 = 0;
}
if(chkBox2.isChecked){
//store value of this checkbox into one variable i.e.
value2 = value of chkBox2;
}else{
// reset value for this chkBox2 i.e
value2 = 0;
}
int sum = value1 + value2;
textView.setText(sum + "");
Use OnCheckedChangeListeners to do your task
chkBox1.setOnCheckedChangeListener(eventListener);
chkBox2.setOnCheckedChangeListener(eventListener);
CompoundButton.OnCheckedChangeListener eventListener=new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
switch (buttonView.getId())
{
case R.id.chk1;
if(isChecked)
{
//do your first task
//set your textbox values
}
break;
case R.id.chk2:
if(isChecked)
{
//do your second task
//set your second text values
}
break;
}
}
};
if you dont have t0o many check box and iteration is fine than you can try following code.
public void addUserType(ProObj obj)
{
final CheckBox cb = new CheckBox(getActivity());
cb.setText(obj.getamount());
cb.setTag(obj);
layUsertype.post(new Runnable() {
public void run() {
layUsertype.addView(cb);
}
});
//any listener method
cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
double sum = 0.0;
int childcount = layUsertype.getChildCount();
for (int i=0; i < childcount; i++){
View v = layUsertype.getChildAt(i);
if(v instanceof CheckBox)
{
CheckBox cb = (CheckBox)v;
if(cb.isChecked())
{
if(cb.getTag() instanceof ProObj )
{
sum+=((UserTypesObj) cb.getTag()).getamount();
}
}
}
}
}
//update logic
});
}
I am looking for something similar in android where I can add radiobuttons to each cells in Table and get their position. Does anyone has worked on it before, if you can share the sample code would be helpful. Thanks
The following pseudocode should get you started:
//create a radio group
RadioGroup rg = new RadioGroup(context);
RadioGroup.LayoutParams rgParams = new RadioGroup.LayoutParams(
RadioGroup.LayoutParams.WRAP_CONTENT,
RadioGroup.LayoutParams.WRAP_CONTENT);
rg.setLayoutParams(rgParams);
//add the radio group to the row.
rowView.addView(rg);
//add radio buttons
for (i = 0; i < length; i++) {
RadioButton btn = new RadioButton(context);
btn.setText(description[i]);
//or save an object which will hold all information you need
btn.setTag(rowNumber);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, v.getTag());
}
});
if (<some condition>) {
btn.setChecked(true);
}
rg.addView(btn);
}
I have created a layout dynamically and added check boxes. code as follows,
//Load dynamic view
List<Integer> checkBoxIdList = new ArrayList<Integer>();
int id = 0;
ScrollView sv = new ScrollView(this);
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
sv.addView(ll);
TextView tv = new TextView(this);
tv.setText("CatchInfo");
tv.setTextColor(Color.rgb(200,0,0));
ll.addView(tv);
for(int i=0;i<list2.size();i++)
{
ck = new CheckBox(this);
ck.setId(id);
checkBoxIdList.add(id);
ck.setText(list2.get(i));
ll.addView(ck);
}
Button btnHome = new Button(this);
btnHome.setText("Home");
ll.addView(btnHome);
Button btnSubmit = new Button(this);
btnSubmit.setText("Submit");
ll.addView(btnSubmit);
this.setContentView(sv);
I am trying get value value of check box using click listner as follows:
ck.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
if(!isChecked){
Toast.makeText(getApplicationContext(), "Yes",
Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(getApplicationContext(), "No",
Toast.LENGTH_LONG).show();
}
}
});
But the click action is only taken place in last check box and in others it is not responding. How can solve this and how will I get values?
You need to create your function to handle the onCheckedChangeListener.. See the below code.
List<Integer> checkBoxIdList = new ArrayList<Integer>();
int id = 0;
String[] list2 = {"A", "B", "C", "D", "E"};
ScrollView sv = new ScrollView(this);
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
sv.addView(ll);
TextView tv = new TextView(this);
tv.setText("CatchInfo");
tv.setTextColor(Color.rgb(200,0,0));
ll.addView(tv);
for(int i=0;i<list2.size();i++)
{
ck = new CheckBox(this);
ck.setId(id);
checkBoxIdList.add(id);
ck.setTag(list2[i]); // set the tag values so that you can refer to them later.
ll.addView(ck);
ck.setOnCheckedChangeListener(handleCheck(ck)); //Calling the function, add this line in your code
}
Button btnHome = new Button(this);
btnHome.setText("Home");
ll.addView(btnHome);
Button btnSubmit = new Button(this);
btnSubmit.setText("Submit");
ll.addView(btnSubmit);
this.setContentView(sv);
Here is the function which handles the check events
private OnCheckedChangeListener handleCheck (final CheckBox chk)
{
return new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
if(!isChecked){
Toast.makeText(getApplicationContext(), "You unchecked " + chk.getTag(),
Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(getApplicationContext(), "You checked " + chk.getTag(),
Toast.LENGTH_LONG).show();
}
}
};
}
You have to do like this.
for(int i=0;i<list2.size();i++)
{
CheckBox ck = new CheckBox(this);
ck.setId(id);
checkBoxIdList.add(id);
ck.setText(list2.get(i));
ck.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
if(!isChecked){
Toast.makeText(getApplicationContext(), "Yes",
Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(getApplicationContext(), "No",
Toast.LENGTH_LONG).show();
}
}
});
ll.addView(ck);
}
you forgot to increment in id variable.
thats y all checkboxes you are adding will get same id.
List<CheckBox> checkBoxesList2 = new ArrayList<CheckBox>();
for(int i=0;i<list2.size();i++)
{
ck = new CheckBox(this);
ck.setId(id);
checkBoxIdList.add(id);
checkBoxesList2.add(ck);
id++;
ck.setText(list2.get(i));
ll.addView(ck);
}
for(int i=0;i<checkBoxesList2.size();i++){
ck =(CheckBox) checkBoxesList2.get(i);
ck.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
if(!isChecked){
Toast.makeText(getApplicationContext(), "Yes",
Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(getApplicationContext(), "No",
Toast.LENGTH_LONG).show();
}
}
});
}