I'm new to android, I have a button that is when its clicked it will get the double value from an EditText and show it in a TextView.
Also I have two radio buttons, one is positive and other is negative, I want when the user toggle the negative button to multiply the double by -1, my code is like:
public void buttonClicked(View view) {
try {
myDouble = Double.parseDouble((myDoubleEditText.getText().toString()));
} catch (NumberFormatException e) {
Toast.makeText(getApplicationContext(), "Enter a valid Double", LENGTH_LONG).show();
}
myTextView.setText("My Double is",""+myDouble)
}
public void onRadioButtonClicked(View view) {
boolean checked = ((RadioButton) view).isChecked();
switch(view.getId()) {
case R.id.positive:
if (checked)
myDouble = myDouble;
break;
case R.id.negative:
if (checked)
myDouble = myDouble * -1;
break;
}
}
}
Please guide me to do it.
Thanks
I'd think a better way is to use RadioGroup and set the listener on this to change and update the View accordingly (saves you having 2 or 3 or 4 etc listeners).
RadioGroup radioGroup = (RadioGroup) findViewById(R.id.yourRadioGroup);
radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// checkedId is the RadioButton selected
switch(checkedId) {
case R.id.positive:
myDouble = myDouble;
break;
case R.id.negative:
myDouble = myDouble * -1;
break;
}
}
});
Related
I have a quiz app that should contains the following:
1- radio groups/buttons
2- checkbox
3- editText
all should calculate a score. I manage to get the radio groups, checkbox to work and calculate the score. however having problems with the editText
I am trying to compare the value of what's in name2 variable but I am unable to do so. I've implemented the .equals syntax but it's not working accordingly.
Any suggestions/solutions are grateful.
public class Quiz extends AppCompatActivity {
int score = 0;
String name;
String name2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
}
public void onRadioButtonCliked(View view) {
Boolean checked = ((RadioButton) view).isChecked();
switch (view.getId()) {
case R.id.yes_radio_buttonG1B3:
if (checked)
score++;
break;
case R.id.yes_radio_buttonG2B2:
if (checked)
score++;
break;
case R.id.yes_radio_buttonG3B2:
score++;
if (checked)
break;
case R.id.yes_radio_buttonG4B1:
if (checked)
score++;
break;
case R.id.yes_radio_buttonG5B2:
if (checked)
score++;
break;
case R.id.yes_radio_buttonG6B3:
if (checked)
score++;
break;
}
}
public void onCheckBoxCliked(View view) {
Boolean checked = ((CheckBox) view).isChecked();
CheckBox cB1 = (CheckBox) findViewById(R.id.checkBox1);
CheckBox cB2 = (CheckBox) findViewById((R.id.checkBox2));
CheckBox cB3 = (CheckBox) findViewById(R.id.checkBox3);
if (cB1.isChecked() && cB2.isChecked() && !cB3.isChecked()) {
score++;
}
}
public void EditText(View view) {
EditText text = (EditText) findViewById(R.id.editText1);
name2 = text.getText().toString();
if (name2.equals("8")) {
score++;
}
}
public void submitOrder(View view) {
EditText username = (EditText) findViewById(R.id.editText);
name = username.getText().toString();
Toast.makeText(this, "Thank you " + name, Toast.LENGTH_SHORT).show();
Toast.makeText(this, "You have got 8/" + score, Toast.LENGTH_SHORT).show();
}
}
Since it's a string variable, you must use "" to indicate it's a string.
Whole number are only applicable for int variable type.
if(name2.equals("8")){
score++;
}
Try replacing the 8 with "8" as you are supposed to be comparing a String, not an integer.
As already mentioned in a comment and in the two other answers, you can't compare a String to a number.
Instead of checking a String, convert that string to an integer(assuming it is a valid int) and compare the ints instead.
First, convert:
int value;
try{
value = Integer.parseInt(name2);//throws an exception if it isn't a valid integer or if name == null
}catch(Exception e){
return;//not valid, don't continue
}
Then compare:
if(value == 8){
score++;
}
RadioGroup provide method "set()" for OnCheckedChangeListener, but not "get()". But my module must in some way get OnCheckedChangeListener of RadioGroup and wrap it with my listener, which provide tracking of behavior for customer. How can I get this OnCheckedChangeListener listener without asking user of my library to provide it explicitly as parameter?
Sample of problem:
we can implement method:
void wrapMyRadioGroup(RadioGroup group,OnCheckedChangeListener listener){
group.setOnCheckedChangeListener(new SomeCompositeListener(listener));
}
but can't some like this:
void wrapMyRadioGroup(RadioGroup group){
group.setOnCheckedChangeListener(new SomeCompositeListener(group.getOnCheckedChangeListener()));
}
And,as you can gues, we need last one.
P.S.
I've found solution with reflection.
private void trackRadioGroup(RadioGroup radioGroup){
RadioGroup.OnCheckedChangeListener listener = null;
try {
Field field = radioGroup.getClass().getDeclaredField("mOnCheckedChangeListener");
field.setAccessible(true);
Object value = field.get(radioGroup);
if(value !=null){
listener = (RadioGroup.OnCheckedChangeListener)value;
}
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
radioGroup.setOnCheckedChangeListener(new SomeCompositeListener(listener));
}
Thanks all for understanding and rates...
try this
RadioGroup radioGroup = (RadioGroup)findViewById(R.id.cancle_booking_radio_group);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
View radioButton = radioGroup.findViewById(checkedId);
int index = radioGroup.indexOfChild(radioButton);
switch (index) {
case 0:
// perform your action here
break;
case 1:
// perform your action here
break;
case 2:
// perform your action here
break;
case 3:
// perform your action here
break;
case 4:
// perform your action here
break;
}
}
});
I am currently developing a questionnaire based application where by there are options. I need to assign numerical values to each radio button so when one of it is selected it will give a certain amount of points which will then be used to produce a cumulative amount. I need help in coding the java to do this. any help will be greatly appreciated. Thank you!
int score = 0;
public TextView tv;
public void onRadioButtonClicked(View view) {
boolean checked = ((RadioButton) view).isChecked();
switch (view.getID()) {
case R.id.radioButton1:
if(checked)
score +=1;
break;
case R.id.radioButton2:
if(checked)
score +=1;
break;
case R.id.radioButton3:
if(checked)
score +=3;
break;
}
}
public void updateScore(int score) {
tv = (TextView)findViewById(R.id.textview1);
tv.setText(" " + score);
}
in the XML I have coded a textview with "0" and a text id of #+id/textview1
the issue is that the score remains at 0 even if any radio buttons are selected
Make the following changes to your code
public TextView tv;
int score = 0;
public void onRadioButtonClicked(View view) {
boolean checked = ((RadioButton) view).isChecked();
switch (view.getId()) {
case R.id.radioButton1:
if (checked) {
score += 1;
}
break;
case R.id.radioButton2:
if(checked)
score +=1;
break;
case R.id.radioButton3:
if(checked)
score +=3;
break;
}
updateScore(score); // <- Added this line here
}
public void updateScore(int score) {
// Don't initialise your view here. Take it to onCreate()
tv.setText(" " + score);
}
EDIT
Is your XML for the radio button similar to what I have here?
<RadioButton
android:id="#+id/radioButton1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="asas"
android:onClick="onRadioButtonClicked"/>
Make sure you have added the android:onClick="onRadioButtonClicked" property to each of the radio buttons
I have set the click event listener on a number of CheckBox and RadioButton views. Both of these view types have an isChecked() method. I can get the state of either one by casting to its type for every single switch case, but can I get the state just in a general sense for either of them before I enter the switch cases?
#Override
public void onClick(View view) {
boolean checkState;
switch (view.getId()) {
case R.id.radio_button_1:
checkState = ((RadioButton) view).isChecked();
// ...
break;
case R.id.check_box_1:
checkState = ((CheckBox) view).isChecked();
// ...
break;
// more check boxes and ratio buttons ...
}
}
This question has a similar title to this one, but there was too much code there for me to easily understand if they were asking the same thing.
While I was in the process of writing this question, I found an answer, which I will post below. However, if there is a better answer, I will accept it.
Consider one RadioButton and one CheckBox
RadioButton button = (RadioButton) findViewById(R.id.radio_button);
button.setOnCheckedChangeListener(listener);
CheckBox box = (CheckBox) findViewById(R.id.checkbox);
box.setOnCheckedChangeListener(listener);
Both have a single listener
CompoundButton.OnCheckedChangeListener listener = new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(buttonView instanceof CheckBox ){
Toast.makeText(getApplicationContext(), "ChechBox " + String.valueOf(isChecked), Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(getApplicationContext(), "RadionButton " + String.valueOf(isChecked), Toast.LENGTH_SHORT).show();
}
}
};
If there are many still we can use a single listener as follows
CompoundButton.OnCheckedChangeListener listener = new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(buttonView instanceof CheckBox ){
final ChechBox b = (ChechBox)buttonView;
switch(b.getId()){
case R.id.first_checkbox:
. . . . . . . .
}
}else {
final RadioButton r = (RadioButton)buttonView;
switch(r.getId()){
case R.id.first_radio
. . . . . . . . . . .
}
}
}
};
You need to attach all of the views to this listener
Direct Answer
As #MikeM answered in the comments, you can use instanceof to check once for CompoundButton or Checkable and cast to that.
#Override
public void onClick(View view) {
boolean checkState = false;
if (view instanceof Checkable) {
checkState = ((Checkable) view).isChecked();
}
switch (view.getId()) {
// ...
}
}
Better Answer
However, as #MikeM also mentioned, you should be using an OnCheckedChangeListener rather than an OnClickListener. There are two similar checked changed listeners:
CompoundButton.OnCheckedChangeListener
RadioGroup.OnCheckedChangeListener
The CompoundButton listener can be used for a CheckBox or a RadioButton. However, if all the radio buttons in a RadioGroup had this set, the listener would get called twice, once for the button getting turned off and once for the button getting turned on. Thus, it is better to use the RadioGroup listener for radio buttons.
So add the RadioGroup.OnCheckedChangeListener to the RadioGroup and the CompoundButton.OnCheckedChangeListener to each CheckBox.
// set RadioGroup.OnCheckedChangeListener
RadioGroup rg = (RadioGroup) view.findViewById(R.id.radio_group);
rg.setOnCheckedChangeListener(radioGroupListener);
// set `CompoundButton.OnCheckedChangeListener`
CheckBox cb1 = (CheckBox) view.findViewById(R.id.check_box_1);
cb1.setOnCheckedChangeListener(checkBoxListener);
CheckBox cb2 = (CheckBox) view.findViewById(R.id.check_box_2);
cb2.setOnCheckedChangeListener(checkBoxListener);
// ...
where the listeners are implemented as follows:
Radio Buttons
The isChecked() value is true for whatever RadioButton id is returned by the RadioGroup listener.
RadioGroup.OnCheckedChangeListener radioGroupListener = new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, int checkedId) {
// checkedId is the id of the newly checked radio button
switch (checkedId) {
case R.id.radio_button_1:
// ...
break;
case R.id..radio_button_2:
// ...
break;
// ...
}
}
};
Check Boxes
The isChecked value is directly passed in to the CompoundButton listener.
CompoundButton.OnCheckedChangeListener checkBoxListener = new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
switch (compoundButton.getId()) {
case R.id.checkbox_1:
// ...
break;
case R.id.checkbox_2:
// ...
break;
}
}
};
I want to do an Android App Quiz. I did a radiogroup with 4 radiobuttons that represent the 4 answers.
I want that when these radiobuttons aren't clicked the app shows an error, but my doesn't do it.
This my code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
RadioGroup champ=(RadioGroup)findViewById(R.id.answer1);
champ.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#SuppressWarnings("null")
public void onCheckedChanged(RadioGroup group, int checkedId) {
// TODO Auto-generated method stub
switch(checkedId) {
case R.id.answer1A:
ans1 =0;
break;
case R.id.answer1B:
ans1 =1;
break;
case R.id.answer1C:
ans1 =2;
break;
case R.id.answer1D:
ans1 =3;
break;
case R.id.answer1E:
ans1 =4;
break;
default:
ans1=(Integer) null;
Toast.makeText(MainActivity.this, "error", Toast.LENGTH_LONG).show();
break;
}
}
});
Why?Can you help me, please?
First assign:
ans1=-1; //in onCreate or at the time of declaration
You might be having a button or something clicking on which you would be accessing which answer was checked, there you can check :
if(ans1==-1)
{
//show error message
}
else
{
//Success
}
This check is not executing because this is a checkedchangelistener which will trigger when you click on some radiobutton (when status is changed).
All you have to do is Check the status of the each and every radiobutton outside this listener.