Simple problem to fix (I hope)...can't figure it out myself though.
I need one radio button to be un-checked or un-selected when the other is checked/selected.
Here is my code. Right now the app works fine but when the user goes to change the selection the first button doesn't clear:
Button convert = (Button) findViewById(R.id.btnConvert);
convert.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
weightEntered=Double.parseDouble(weight.getText().toString());
DecimalFormat tenth = new DecimalFormat("#.#");
if (lbToKilo.isChecked()) {
if (weightEntered <= 500) {
convertedWeight = weightEntered / conversionRate;
result.setText(tenth.format(convertedWeight) + " kilograms");
} else {
Toast.makeText(getApplicationContext(), "Pounds must be less than 500.", Toast.LENGTH_LONG).show();
}
}
if (kiloToLb.isChecked()) {
if (weightEntered <= 225) {
convertedWeight = weightEntered * conversionRate;
result.setText(tenth.format(convertedWeight) + " pounds");
} else {
Toast.makeText(getApplicationContext(), "Kilos must be less than 225.", Toast.LENGTH_LONG).show();
}
}
}
});
You simply need to group your RadioButtons in a RadioGroup.
That's all you need to get some mutually exclusive RadioButtons.
For your reference: http://developer.android.com/guide/topics/ui/controls/radiobutton.html
Related
I am making an app which is a guessing game between 1 and 100. The current version I am writing gives the player 7 tries to to find the correct guess. I have created a variable to display how many guesses the player has left, however once the player has guessed, the number of guesses decrements by more than one (usually two).
So basically the numberOfGuesses var. will decrement every time the checkGuess() method is run. I have tried placing the decrement in the event listener for when the player presses the button, but it's still decrementing by more than one. There is a setOnClick listener if the player clicks the mouse button too, and another for the enter button. When I use the button in the game, it decrements properly. When I use the ENTER button, it decrements by two. Is it running the button listener when I press ENTER?
I tried changing decrement from numberOfGuesses--; to --numberOfGuesses;
I tried assigning it as numberOfGuesses = numberOfGuesses - 1;
Here is the variables wiring to thew GUI, and the checkGuess() method
public class MainActivity extends AppCompatActivity {
private EditText txtGuess;
private Button btnGuess;
private TextView lblOutput;
private int theNumber;
private int numberOfTries = 7;
public void checkGuess() {
String guessText = txtGuess.getText().toString();//
String message = "";
try {
--numberOfTries;
int guess = Integer.parseInt(guessText);
if (guess > theNumber)
message = guess + " is too high. You have " +numberOfTries + " " + " tries left! ";
else if (guess < theNumber)
message = guess + " is too low. You have " +numberOfTries + " " + " tries left! ";
else{
message = guess +
" is correct! You finished with " +numberOfTries + " tries left. Let's play again!";
Toast.makeText(MainActivity.this, message,
Toast.LENGTH_LONG).show();
newGame();
}
} catch (Exception e) {
message = "Enter a whole number between 1 and 100.";
} finally {
lblOutput.setText(message);
txtGuess.requestFocus();
txtGuess.selectAll();
The newGame() method which generates a new random number
public void newGame(){
theNumber = (int)(Math.random() * 100 + 1);
numberOfTries = 7;
}
Here is the method which runs on execution of app
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtGuess = (EditText) findViewById(R.id.txtGuess);
btnGuess = (Button) findViewById(R.id.btnGuess);
lblOutput = (TextView) findViewById(R.id.lblOutput);
newGame();
btnGuess.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkGuess();
}
});
txtGuess.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
checkGuess();
return true;
}
});
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
I am expecting the numberOfGuesses to decrement from 7 to 6, but the actual output is decrementing from 7 to 5, when I use enter, it works as I want for the button click (or at least displaying as 7 to 5),
Pressing enter while the text field is selected would trigger the OnEditorActionListener (and so would any other change, as far as I can tell). Have you tried filtering that Listener by actionId to make sure it only goes off specifically for the enter key?
I started learning Android Development. I was building a basic addition game, where user has to click on button which shows the addition of two number. There are four Textviews. First one give the time limit for each question to answer. Second gives the question for the user. Third one gives the current score of the user and the last one gives whether the chosen open is correct or incorrect.
Everything is working except the First Button. Every time when the button is pressed the the counting takes very fast.
// When First button is pressed
public void onClickButton1(View view) {
correctIncorrect.setVisibility(View.VISIBLE);
if (Integer.parseInt(button1.getText().toString())==sum) {
correctIncorrect.setText("Correct");
correctUpdater();
}
else {
correctIncorrect.setText("Incorrect");
inCorrectUpdater();
}
}
//Similar to all the buttons
//To Update the score
public void correctUpdater() {
n++;
yourScore++;
score.setText(Integer.toString(yourScore) + "/" + Integer.toString(n));
update();
}
public void inCorrectUpdater() {
n++;
score.setText(Integer.toString(yourScore) + "/" + Integer.toString(n));
update();
}
// To update the timer
//=======================================================================//
public void resetTimer() {
timer.setText(Integer.toString(temp)+"s");
if (temp == 0) {
inCorrectUpdater();
update();
}
else {
timeUpdater();
}
}
public void timeUpdater() {
Handler timeHandler = new Handler();
Runnable timeRunnable = new Runnable() {
#Override
public void run() {
temp--;
resetTimer();
}
};
timeHandler.postDelayed(timeRunnable,1000);
}
//=================================================================//
// Updater function
public void update() {
correctIncorrect.setVisibility(View.INVISIBLE);
Random random = new Random();
int a = random.nextInt(21);
int b = random.nextInt(21);
question.setText(Integer.toString(a) + " + " + Integer.toString(b));
Log.i("info", "onCreate: a = " + a);
Log.i("info", "onCreate: b = " + b);
sum = a+b;
Log.i("info", "onCreate: sum = " + sum);
int whichButton = random.nextInt(4);
Log.i("info", "onCreate: random button is " + whichButton);
values.clear();
for (int i = 0; i< 4; i++) {
if (i == whichButton) {
values.add(sum);
}
else {
values.add(random.nextInt(50));
}
Log.i("info", "onCreate: value[" + i + "] = " + values.get(i));
}
button1.setText(Integer.toString(values.get(0)));
button2.setText(Integer.toString(values.get(1)));
button3.setText(Integer.toString(values.get(2)));
button4.setText(Integer.toString(values.get(3)));
temp = 10;
resetTimer();
}
Am I using the Handler incorrectly? What can I do?
Am I using the Handler incorrectly? What can I do?
A better way to do this is CountDownTimer, by using this you won't have to deal with Handler youself and you also have a provision to cancel a running CountDownTimer.
Everything is working except the First Button
Not really sure what can cause different behaviours on click of buttons with the same code in onClick(). But you can consider using the same onClickListener for all the 4 buttons, in this way :
View.OnClickListener myListener = new View.OnClickListener() {
#Override
public void onClick(View button) {
correctIncorrect.setVisibility(View.VISIBLE);
if (Integer.parseInt(button.getText().toString())==sum) {
correctIncorrect.setText("Correct");
correctUpdater();
}
else {
correctIncorrect.setText("Incorrect");
inCorrectUpdater();
}
}
};
button1.setOnClickListener(myListener);
button2.setOnClickListener(myListener);
button3.setOnClickListener(myListener);
button4.setOnClickListener(myListener);
This will ensure that clicking any of the 4 buttons will have a same behavior (depending on the answer of course)
In case you get confused with the onTick() method on CountDownTimer, you can use modified CountDownTimer which will ensure that the timer doesn't miss any ticks.
I have a problem related click count. The problem is, I can't stop click when a number a click is given.
For example, I allow users to click a button 3 times, if clicks reached 3 times, then stop count, and do what I want.
This is my code I have used.
private int clickcount = 3;
#Override
public void onClick(View v) {
// Do button click handling here
if ( posisi2==getAdapterPosition() ) {
clickcount--;
tombolbaca.setText("Baca " + clickcount + "x");
// try to stop count but it can't, computer still counting
if (clickcount == 3)
{
mTitle.setVisibility(View.GONE);
rl2.setVisibility(View.GONE);
}
} // adapter
} // onClick
I think the trigger to do something might be when the click count is zero, not three:
if (clickcount == 0) {
mTitle.setVisibility(View.GONE);
rl2.setVisibility(View.GONE);
}
It isn't clear whether the above if statement belongs nested inside the outer if, or if it should be at the method level of onClick().
Note: We could have written if (clickCount <= 0), but there may not be a need to do this (nor may it be desirable), since after you have changed the visibility of those elements to GONE once, you don't need to do it again.
Make this Change,
private int clickcount = 3;
#Override
public void onClick(View v) {
// Do button click handling here
if ( posisi2==getAdapterPosition() ) {
clickcount--;
tombolbaca.setText("Baca " + clickcount + "x");
// try to stop count but it can't
if (clickcount <=0) <== make this change
{
mTitle.setVisibility(View.GONE);
rl2.setVisibility(View.GONE);
}
} // adapter
}
try this
private int clickcount = 3;
#Override
public void onClick(View v) {
// Do button click handling here
if ( posisi2==getAdapterPosition() ) {
clickcount--;
tombolbaca.setText("Baca " + clickcount + "x");
// try to stop count but it can't, computer still counting
if (clickcount == 0)
{
mTitle.setVisibility(View.GONE);
rl2.setVisibility(View.GONE);
}
} // adapter
} // onClick
private int clickcount = 0;
#Override
public void onClick(View v) {
// Do button click handling here
if ( clickcount<3 ) {
clickcount++;
tombolbaca.setText("Baca " + clickcount + "x");
}
//Count stops here..
else
{
mTitle.setVisibility(View.GONE);
rl2.setVisibility(View.GONE);
}
}
}
I am making android app and I have edit text surrounded by two buttons for increase and decrease
and when I click the button increase or decrease for the first time it did not work but it start working from the second time
e.g if the number in edit text field is 50 when I press increase it still 50 when I press increase again it change to 51 and again it change to 52 and so on
here is my java code for the two buttons
add.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (quantityEdit.getText().toString().equals("") || quantityEdit.getText().toString() == null) {
quantityEdit.setText("0");
} else {
int a = Integer.parseInt(quantityEdit.getText().toString());
int b = a + 1;
quantityEdit.setText(String.valueOf(b));
}
}
});
sub.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int a = Integer.parseInt(quantityEdit.getText().toString());
if (a >= 1) {
int b = a - 1;
quantityEdit.setText(String.valueOf(b));
} else {
quantityEdit.setText("0");
}
}
});
It looks like you are checking for empty string or null in "add", but not in "sub". As Michael Krause said, you should use TextUtils.isEmpty(), and set a default value before performing add or sub operations.
If you are setting a default value elsewhere, please show your code.
Consider refactoring your code like so
add.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
quantityEdit.setText(String.valueOf(getIntVal(quantityEdit) + 1));
}
});
sub.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int value = getIntVal(quantityEdit);
if (value > 0) {
value--;
}
quantityEdit.setText(String.valueOf(value));
}
});
// helper method to get the integer value of a TextView
private int getIntVal(TextView textView) {
CharSequence rawValue = textView.getText();
int value;
if (!TextUtils.isEmpty(rawValue)) {
try {
value = Integer.parseInt(rawValue.toString());
} catch (NumberFormatException e) {
value = 0;
// TODO log / notify user
}
} else {
value = 0;
}
}
This way your initialization is handled in one place and it's more clear.
In any event, your first condition is wrong. You do a null check after trying to access the object (it's backwards). Have you checked your logs? This could throw an exception for a null value and "lose" the first click.
Hello everyone so i'm pretty new to Java and this code below will surely prove it.
I'd greatly appreciate any tip upon where i've gone wrong, thanks!
I'm trying to create a simple app that displays a random quote, and gives the chance to guess who said it.
Pretty sure the main issue has to do with ---> if (guessNameInt == whoSaidItInt)
because it only crashes when i click the button which enables the tryLuck if statement.
Heres my code below
int randomNum;
String whoSaidIt;
// quotes and numbers
public void randomRick(View view) {
if (randomNum == 0) {
Toast.makeText(getApplicationContext(), "Life is effort and I'll stop when I die!", Toast.LENGTH_LONG).show();
whoSaidIt = "Jerry";
}
if (randomNum == 1) {
Toast.makeText(getApplicationContext(), "Well look where being smart got you.", Toast.LENGTH_LONG).show();
whoSaidIt = "Jerry";
}
if (randomNum == 2) {
Toast.makeText(getApplicationContext(), "Ohh yea, you gotta get schwifty.", Toast.LENGTH_LONG).show();
whoSaidIt = "Rick";
}
}
public void tryLuck(View view) {
EditText guessedName = (EditText) findViewById(R.id.authorIs);
String guessedNameString = guessedName.getText().toString();
int guessNameInt = Integer.parseInt(guessedNameString);
int whoSaidItInt = Integer.parseInt(whoSaidIt);
if (guessNameInt == whoSaidItInt) {
Toast.makeText(getApplicationContext(), "Holy crow, Good job!", Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(getApplicationContext(), "Try again", Toast.LENGTH_LONG).show();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Random randomGenerator = new Random();
randomNum = randomGenerator.nextInt(3);
}`
You're trying to convert a String to an Int. This will only work if the String is an actual int (ie a number), and not the name (Jerry or Rick). Use guessNameString.equals(whoSaidIt) instead.