How to disable the Onclick of RadioButton once it is clicked? - java

I am creating a quiz app where in it asks a question and gives users options.For options I have used RadioButton So what I want is that once the user clicked any one of the options it should not allow any other options to be clicked but the problem is that it can be still clicked.if possible please write the code.Thanks!
private int Question_no=0;
private Boolean Boolean_Var=false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_question1);
String[] Question_Array = getResources().getStringArray(R.array.Question1);
TextView Questions = (TextView) findViewById(R.id.Question);
Questions.setText(Question_Array[Question_no]);
String[] Radio_Button1_Array = getResources().getStringArray(R.array.Option_1);
RadioButton Radio_Button1 = (RadioButton) findViewById(R.id.radioButton1);
Radio_Button1.setText(Radio_Button1_Array[Question_no]);
String[] Radio_Button2_Array = getResources().getStringArray(R.array.Option_2);
RadioButton Radio_Button2 = (RadioButton) findViewById(R.id.radioButton2);
Radio_Button2.setText(Radio_Button2_Array[Question_no]);
findViewById(R.id.MenuButton).setVisibility(View.INVISIBLE);
findViewById(R.id.NextButton).setVisibility(View.INVISIBLE);
}
public void On_RadioButton1_Click (View view)
{
if (Boolean_Var == false) {
String[] CorrectAns_Array = getResources().getStringArray(R.array.Answer1);
String CorrectAns = CorrectAns_Array[Question_no];
String[] Answer_Array = getResources().getStringArray(R.array.Option_1);
String Answer = Answer_Array[Question_no];
if (Answer.equals(CorrectAns)) {
RadioButton Right_Ans = (RadioButton) findViewById(R.id.radioButton1);
Right_Ans.setTextColor(Color.GREEN);
AnswerSubmitted();
} else {
RadioButton Wrong_Ans = (RadioButton) findViewById(R.id.radioButton1);
Wrong_Ans.setTextColor(Color.RED);;
GreenTick();
AnswerSubmitted();
}
}
Boolean_Var = true;
}
public void On_RadioButton2_Click(View view)
{
if(Boolean_Var==false)
{
String[] CorrectAns_Array = getResources().getStringArray(R.array.Answer1);
String CorrectAns = CorrectAns_Array[Question_no];
String[] Answer_Array = getResources().getStringArray(R.array.Option_2);
String Answer = Answer_Array[Question_no];
if(Answer.equals(CorrectAns))
{
RadioButton Right_Ans = (RadioButton) findViewById(R.id.radioButton2);
Right_Ans.setTextColor(Color.GREEN);
}
else
{
RadioButton Wrong_Ans = (RadioButton) findViewById(R.id.radioButton2);
Wrong_Ans.setTextColor(Color.RED);
GreenTick();
}
}
Boolean_Var=true;
AnswerSubmitted();
}
public void GreenTick()
{
String[] Answer1_Array = getResources().getStringArray(R.array.Option_1);
String Answer1 = Answer1_Array[Question_no];
String[] Answer2_Array = getResources().getStringArray(R.array.Option_2);
String Answer2 = Answer2_Array[Question_no];
String[] Answer3_Array = getResources().getStringArray(R.array.Option_3);
String Answer3 = Answer3_Array[Question_no];
String[] The_CorrectAns_Array = getResources().getStringArray(R.array.Answer1);
String The_CorrectAnsIs = The_CorrectAns_Array[Question_no];
if(The_CorrectAnsIs.equals(Answer1))
{
Button Option_with_CorrectAns = (Button) findViewById(R.id.radioButton1);
Option_with_CorrectAns.setTextColor(Color.GREEN);
}
else if(The_CorrectAnsIs.equals(Answer2))
{
Button Option_with_CorrectAns = (Button) findViewById(R.id.radioButton2);
Option_with_CorrectAns.setTextColor(Color.GREEN);
}
else if(The_CorrectAnsIs.equals(Answer3))
{
Button Option_with_CorrectAns = (Button) findViewById(R.id.radioButton3);
Option_with_CorrectAns.setTextColor(Color.GREEN);
}
else
{
Button Option_with_CorrectAns = (Button) findViewById(R.id.radioButton4);
Option_with_CorrectAns.setTextColor(Color.GREEN);
}
}
public void AnswerSubmitted()
{
findViewById(R.id.MenuButton).setVisibility(View.VISIBLE);
findViewById(R.id.NextButton).setVisibility(View.VISIBLE);
}
}

try this after click on radiobutton :
yourradioButtonId.setClickable(false);

You can use setClickable(false);.For this:
yourradiobutton.setClickable(false);

If I'm understanding correctly, you want to disable the RadioGroup once a certain RadioButton is clicked. Just add an OnCheckedChangedListener and if the id of the RadioButton clicked is the right one, then disable the group by using setEnabled(false). Of course, you can't reenable the RadioGroup unless you have some other logic in your code that will do the re-enabling.
RadioGroup radioGroup = (RadioGroup)findViewById (R.id.radioGroup1);
radioGroup.setOnCheckedChangedListener (new OnCheckedChangedListener(){
public void onCheckedChanged(RadioGroup group, int checkedId)
{
if (checkedId == R.id.radio0)
group.setEnabled(false);
}
});
Edit: It seems that setEnabled() doesn't work, so you should try changing your code so it loops through each RadioButton upon checking radio0:
if (checkedId == R.id.radio0){
for(int i = 0; i < group.getChildCount(); i++){
((RadioButton)rg1.getChildAt(i)).setEnabled(false);
}
}

Related

How to prevent second click on radio button if it was already clicked in Android?

I want to stop the second click on a RadioButton, when someone has already clicked on a RadioButton in a RadioGroup. If someone clicks 2 times, the user not able to change that selected click. I am trying to prevent that with a boolean but it doesn't work. Where am I wrong?
This is my code:
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// checkedId is the RadioButton selected
rb = (RadioButton) findViewById(checkedId);
user_radio_answer = (String) rb.getText();
rb.setOnClickListener(new View.OnClickListener() {
private boolean isChecked = true;
#Override
public void onClick(View v) {
if (isChecked) {
if (rb.isChecked() ) {
isChecked = false;
}
}
if (correct_answer1.equals(user_radio_answer)) {
rb.setBackgroundColor(Color.GREEN);
// Toast.makeText(getApplicationContext(), "Correct ☺ : " + user_radio_answer, Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Incorrect Answer :( ..Correct Answer : " + correct_answer1, Toast.LENGTH_LONG).show();
rb.setBackgroundColor(Color.parseColor("#FF5733"));
answer1 = rb_answer1.getText().toString();
answer2 = rb_answer2.getText().toString();
answer3 = rb_answer3.getText().toString();
answer4 = rb_answer4.getText().toString();
if (answer1.equals(correct_answer1)) {
rb_answer1.setBackgroundColor(Color.GREEN);
}
if (answer2.equals(correct_answer1)) {
rb_answer2.setBackgroundColor(Color.GREEN);
}
if (answer3.equals(correct_answer1)) {
rb_answer3.setBackgroundColor(Color.GREEN);
}
if (answer4.equals(correct_answer1)) {
rb_answer4.setBackgroundColor(Color.GREEN);
}
}
new RadioHttpAsyncTask().execute("http:xxxxxx-xxxxxxxxxx-xxxxxxxx");
}
});
}
});
Just remember if they have answered the question, and remember the view (RadioButton) that spawned the first answer, and check that RadioButton again whenever a RadioButton is clicked. This assumes all RadioButtons in the RadioGroup have the same onClick method.
boolean answered = false;
RadioButton radioAnswer;
public void answer1(View view) {
if (!answered) {
radioAnswer = (RadioButton) view;
answered = true;
} else {
radioAnswer.setChecked(true);
}
}
You can add two methods and then call them when needed. You can add a condition, if the radiobutton is checked then disable the group and if it is not checked then set it to enabled. When you clear your radiogroup you can also set buttons enabled.
public void disableRG() {
for(int i = 0; i < radioGroup.getChildCount(); i++){
((RadioButton)radioGroup.getChildAt(i)).setEnabled(false);
}
}
public void enableRG() {
for(int i = 0; i < radioGroup.getChildCount(); i++){
((RadioButton)radioGroup.getChildAt(i)).setEnabled(true);
}
}
Maybe you can set a global boolean flag.
`private boolean alreadyChecked = false;
radioGroup.setOnCheckedChangeListener(new
RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// checkedId is the RadioButton selected
rb = (RadioButton) findViewById(checkedId);
user_radio_answer = (String) rb.getText();
if (!alreadyChecked) {
rb.setOnClickListener(new View.OnClickListener() {
private boolean isChecked = true;
#Override
public void onClick(View v) {
if (isChecked) {
if (rb.isChecked() ) {
isChecked = false;
}
}
if (correct_answer1.equals(user_radio_answer)) {
rb.setBackgroundColor(Color.GREEN);
// Toast.makeText(getApplicationContext(), "Correct ☺ : " + user_radio_answer, Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Incorrect Answer :( ..Correct Answer : " + correct_answer1, Toast.LENGTH_LONG).show();
rb.setBackgroundColor(Color.parseColor("#FF5733"));
answer1 = rb_answer1.getText().toString();
answer2 = rb_answer2.getText().toString();
answer3 = rb_answer3.getText().toString();
answer4 = rb_answer4.getText().toString();
if (answer1.equals(correct_answer1)) {
rb_answer1.setBackgroundColor(Color.GREEN);
}
if (answer2.equals(correct_answer1)) {
rb_answer2.setBackgroundColor(Color.GREEN);
}
if (answer3.equals(correct_answer1)) {
rb_answer3.setBackgroundColor(Color.GREEN);
}
if (answer4.equals(correct_answer1)) {
rb_answer4.setBackgroundColor(Color.GREEN);
}
}
new RadioHttpAsyncTask().execute("http:xxxxxx-xxxxxxxxxx-xxxxxxxx");
}
alreadyChecked = true;
});
}
}
});`
You can disable it after click to stop listening to click events
rb.setEnabled(false);
Edit:
Or you can remove click listener once it is already clicked
rb.setOnClickListener(null);

App Score from checkboxes

I'm coding a quiz app. When I clicked the score button to see if it worked, it showed I got 0 out of 5 right. I put in all the correct answers, but my code didn't tally anything up. What am I missing? I'm not sure what else to add and could really use the guidance as I am a new coder. I appreciate any help you can give.
int correctAnswers = 0;
// Start score
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void answers(View view) {
RadioButton q1 = (RadioButton) findViewById(R.id.yes_radio_button);
Boolean q1RightAnswer = q1.isChecked();
if (q1RightAnswer) {
correctAnswers += 1;
}
CheckBox q2Box1 = (CheckBox) findViewById(R.id.box1_checkbox);
boolean q2Box1RightAnswer = q2Box1.isChecked();
CheckBox q2Box2 = (CheckBox) findViewById(R.id.box2_checkbox);
boolean q2Box2WrongAnswer = q2Box2.isChecked();
CheckBox q2Box3 = (CheckBox) findViewById(R.id.box3_checkbox);
boolean q2Box3RightAnswer = q2Box3.isChecked();
if (q2Box1RightAnswer)
if (q2Box3RightAnswer) {
correctAnswers += 1;
}
if (q2Box2WrongAnswer) {
correctAnswers += 0;
}
RadioButton q3 = (RadioButton) findViewById(R.id.shuri_radio_button);
Boolean q3RightAnswer = q3.isChecked();
if (q3RightAnswer) {
correctAnswers += 1;
}
RadioButton q5 = (RadioButton) findViewById(R.id.two_radio_button);
Boolean q5RightAnswer = q5.isChecked();
if (q5RightAnswer) {
correctAnswers += 1;
}
EditText q4 = (EditText) findViewById(R.id.wakanda);
String q4RightAnswer = q4.getText().toString();
if (q4RightAnswer.equals(correctAnswers)) {
correctAnswers += 1;
} else {
// incorrect, do nothing
}
}
/**
* This method is called when the score button is clicked.
*/
public void submitScore(View view) {
Button nameField = (Button) findViewById(R.id.score);
String score = nameField.getText().toString();
// Show score message as a toast
Toast.makeText(this, "You got " + correctAnswers + "/5 correct!", Toast.LENGTH_LONG).show();
// Exit this method early because there's nothing left to do
return;
}
}
This will never be true
q4RightAnswer.equals(correctAnswers)
You need to compare matching types, not Strings to integers.
Assuming that's what you're trying to do, either parse the string or convert the int to a String.
You'll get zero printed if none of the checkboxes are marked or answers() is never called. For example, what's the difference between the answers method and the submitScore method? Both take a View parameter, so which one is actually assigned to the click event?
I would suggest doing something like
RadioButton q1, q3, q5;
EditText q4;
Checkbox qBox1, qBox2;
Button submit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
q1 = (RadioButton) findViewById(R.id.yes_radio_button);
// assign other views here
submit = (Button) findViewById(R.id.score);
submit.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
int correctAnswers = 0;
if (q1.isChecked()) correctAnswers += 1;
// TODO: check other inputs
String q4Text = q4.getText().toString();
if (q4Text.equals(String.valueOf(correctAnswers)) {
correctAnswers += 1;
}
// Toast correct answers
}
});
}
Basically, define all views as class level variables, then immediately set them after a content view is available, then only calculate the score when the button is clicked (in other words, wait for user input). Also, reset the score each time the button is clicked.

Android Development. RadioButton keeps unselecting

I am building a little quiz app and let's say on Question 1, I select option B, then submit and the quiz gives me the next question. However for question 2 if I try to select B, the RadioButton quickly unchecks itself and it is completely uncheckable, until I select another radio button and then try B again. The pattern is, whatever option I selected in the previous question, is uncheckable in the next question unless I click on a different radiobutton and then try again. I'm attaching my code. Any help please?
public class MainActivity extends AppCompatActivity {
QuestionBank allQuestions = new QuestionBank();
String pickedAnswer = "", correctAnswer = "";
final int numberOfQuestions = allQuestions.list.size();
int questionNumber = 0;
boolean noSelection = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nextQuestion();
}
private void nextQuestion() {
if (questionNumber <= numberOfQuestions - 1) {
TextView questionLabel = (TextView) findViewById(R.id.question_text_view);
String fullQuestion = allQuestions.list.get(questionNumber).questionSet.get("question").toString();
fullQuestion += "\n\na) " + allQuestions.list.get(questionNumber).questionSet.get("a");
fullQuestion += "\nb) " + allQuestions.list.get(questionNumber).questionSet.get("b");
fullQuestion += "\nc) " + allQuestions.list.get(questionNumber).questionSet.get("c");
fullQuestion += "\nd) " + allQuestions.list.get(questionNumber).questionSet.get("d");
correctAnswer = allQuestions.list.get(questionNumber).questionSet.get("answer").toString();
questionLabel.setText(fullQuestion);
questionNumber++;
} else {
restart();
}
}
public void getSelectedAnswer() {
RadioButton radio_1 = (RadioButton) findViewById(R.id.option1_button);
RadioButton radio_2 = (RadioButton) findViewById(R.id.option2_button);
RadioButton radio_3 = (RadioButton) findViewById(R.id.option3_button);
RadioButton radio_4 = (RadioButton) findViewById(R.id.option4_button);
if (radio_1.isChecked()) {
pickedAnswer = "a";
radio_1.setChecked(false);
} else if (radio_2.isChecked()) {
pickedAnswer = "b";
radio_2.setChecked(false);
} else if (radio_3.isChecked()) {
pickedAnswer = "c";
radio_3.setChecked(false);
} else if (radio_4.isChecked()) {
pickedAnswer = "d";
radio_4.setChecked(false);
} else {
noSelection = true;
}
}
public void submitAnswer(View view) {
getSelectedAnswer();
if (noSelection) {
AlertDialog.Builder a_builder = new AlertDialog.Builder(this);
a_builder.setMessage("Please select an answer!");
a_builder.show();
noSelection = false;
} else {
checkAnswer();
nextQuestion();
}
}
public void checkAnswer() {
if (correctAnswer == pickedAnswer) {
AlertDialog.Builder a_builder = new AlertDialog.Builder(this);
a_builder.setMessage("Right Answer!");
a_builder.show();
} else {
AlertDialog.Builder a_builder = new AlertDialog.Builder(this);
a_builder.setMessage("Wrong Answer!");
a_builder.show();
}
pickedAnswer = "";
correctAnswer = "";
}
public void restart() {
questionNumber = 0;
//Collections.shuffle(allQuestions.list);
nextQuestion();
}
}
call setChecked(false) on all the buttons after submitting or before showing next question

Linearlayout is not able to remove it's child

One Linearlayout I have created and dynamically I am adding RadioGroup and textView in it. When next time I am calling the method, Textview is getting removed but old radio buttons are not getting removed.
Here is the code:
public void setShippingMethods() {
shippingChargesLayout.removeAllViews();
final RadioGroup radioGroup = new RadioGroup(getActivity());
radioGroup.setOrientation(LinearLayout.VERTICAL);
TextView textView = new TextView(getActivity());
textView.setText("Select Shipping Options:");
shippingChargesLayout.addView(textView);
for (int i = 0; i < shippingDetailsList.size(); i++) {
RadioButton radioButton = new RadioButton(getActivity());
radioButton.setText("" + shippingDetailsList.get(i).getMethodTitle() + "-" + (new SessionManager(getActivity()).getCurrency()) + df.format(shippingDetailsList.get(i).getAmount()));
RadioGroup.LayoutParams params = new RadioGroup.LayoutParams(RadioGroup.LayoutParams.WRAP_CONTENT, RadioGroup.LayoutParams.WRAP_CONTENT);
radioGroup.addView(radioButton, params);
radioButton.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
}
shippingChargesLayout.addView(radioGroup);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
shipmentCode = shippingDetailsList.get(i - 1).getCarrierCode();
Log.v("carrierCode", "" + shipmentCode);
}
});
checkout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (radioGroup.getCheckedRadioButtonId() == -1) {
Toast.makeText(getActivity(),"Select shipping options.",Toast.LENGTH_LONG).show();
} else {
completeOrder();
}
}
});
}
Here is the image:
I have made some changes in your code.
public void setShippingMethods() {
shippingChargesLayout.removeAllViews();
final RadioGroup radioGroup = new RadioGroup(getActivity());
RadioGroup.LayoutParams params = new RadioGroup.LayoutParams(RadioGroup.LayoutParams.WRAP_CONTENT, RadioGroup.LayoutParams.WRAP_CONTENT);
radioGroup.setLayoutParams(params);
radioGroup.setOrientation(LinearLayout.VERTICAL);
TextView textView = new TextView(getActivity());
textView.setText("Select Shipping Options:");
shippingChargesLayout.addView(textView);
for (int i = 0; i < shippingDetailsList.size(); i++) {
RadioButton radioButton = new RadioButton(getActivity());
radioButton.setText("" + shippingDetailsList.get(i).getMethodTitle() + "-" + (new SessionManager(getActivity()).getCurrency()) + df.format(shippingDetailsList.get(i).getAmount()));
radioGroup.addView(radioButton);
}
shippingChargesLayout.addView(radioGroup);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
shipmentCode = shippingDetailsList.get(i - 1).getCarrierCode();
Log.v("carrierCode", "" + shipmentCode);
}
});
checkout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (radioGroup.getCheckedRadioButtonId() == -1) {
Toast.makeText(getActivity(),"Select shipping options.",Toast.LENGTH_LONG).show();
} else {
completeOrder();
}
}
});
}

Android | Radio buttons wont do anything and keep pressed

Im trying to make a currency converter homework (i am new to programming)
made everything but the radio button is keeped pressed and isnt doing nothing
(not puting text into the TextView and the radio buttons is locked on "pressed" mode
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_convert);
mResult = (TextView) findViewById(R.id.result);
mToConvert = (EditText) findViewById(R.id.toConvert);
mRadioGroup = (RadioGroup) findViewById(R.id.radioG);
mDollar = (RadioButton) findViewById(R.id.dollar);
Meuro = (RadioButton) findViewById(R.id.euro);
mRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
{
public void onCheckedChanged(RadioGroup rGroup, int checkedId)
{
switch (mRadioGroup.getCheckedRadioButtonId())
{
case R.id.dollar:
Double dollarConvert = Double.valueOf(mToConvert.getText().toString()); //convert the string to int
double price = dollarConvert * 1.28;
mDollar.setChecked(true);
Meuro.setChecked(false);
String result = mToConvert.getText().toString();
mResult.setText(result + price);
break;
case R.id.euro:
Double euroConvert = Double.valueOf(mToConvert.getText().toString()); //convert the string to int
double value = euroConvert * 1.28;
mDollar.setChecked(false);
Meuro.setChecked(true);
String result1 = mToConvert.getText().toString();
mResult.setText(result1 + value);
break;
default:;
}
}
});
}
}
you will need to set RadioGroup.setoncheckedchangelistener for RadioGroup to do some Action when check changes event fire.
mRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
{
public void onCheckedChanged(RadioGroup rGroup, int checkedId)
{
//do your code here
}
});

Categories