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);
}
}
}
Related
My ticTacToe Assigment picture
In onClickListener, I have line button00.setImageResource(R.drawable.x_sign);
but it will be executed only when listener is finished.
How can I force this command to execute immediately?
Condition in onClickListener for imageButton is:
if ((opField[x][y] == 0) && covekNext){ // field is empty and man have turn
button00.setImageResource(R.drawable.x_sign);
} else return;
When In this situation I play field 21 ( second row, first column).
button00.setImageResource(R.drawable.x_sign);
Images wouldnt be swaped! blank field stay blank, not X.
Bug or my coding error.
Thanks.
final ImageButton button00 = findViewById(R.id.imageButton00);
button00.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
x=0;
y=0;
if ((opField[x][y] == 0) && covekNext){
button00.setImageResource(R.drawable.x_sign);
} else return;
covekNext = false;
opField[x][y]= 1;
if(++opWinLines[0]==3|++opWinLines[3]==3|++opWinLines[6]==3){
covekWin(); //button00.setImageResource(R.drawable.x_sign); //command not executed
return;
}
if (++zauzeto<9) {
computerMove(); //button00.setImageResource(R.drawable.x_sign); //command not executed
} else {
nereseno(); //button00.setImageResource(R.drawable.x_sign); //command not executed
}
}
}); // button00.setImageResource(R.drawable.x_sign); executed
I think you are looking for something like this :
final ImageButton button00 = findViewById(R.id.imageButton00);
button00.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
x=0;
y=0;
if ((opField[x][y] == 0) && covekNext){
button00.setImageResource(R.drawable.x_sign);
} else return;
covekNext = false;
opField[x][y]= 1;
if(++opWinLines[0]==3|++opWinLines[3]==3|++opWinLines[6]==3){
button00.setImageResource(R.drawable.x_sign);
covekWin();
return;
}
if (++zauzeto<9) {
button00.setImageResource(R.drawable.x_sign);
computerMove();
} else {
button00.setImageResource(R.drawable.x_sign);
nereseno();
}
}
});
its because u use returnin your code
clicklisteners suppose to listen to clicks while user works with activity's ui
It works in most of cases but not always
You are only swapped the imageResource in first if condition. So when first else part is executed, image is not being swapped. If you want this line to execute every time, place it as first line in onClickListener as follows.
final ImageButton button00 = findViewById(R.id.imageButton00);
button00.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
x=0;
y=0;
//Set the imageResource here
button00.setImageResource(R.drawable.x_sign);
if ((opField[x][y] == 0) && covekNext){
} else return;
covekNext = false;
opField[x][y]= 1;
if(++opWinLines[0]==3|++opWinLines[3]==3|++opWinLines[6]==3){
covekWin();
return;
}
if (++zauzeto<9) {
computerMove();
} else {
nereseno();
}
}
});
Cheers :)
Everybody, thanks a lot!!!!
Everything about this question was my mistake made within some false call in methods: covekWin(); computerWin(); nereseno().
So this part of code is correct, and this question can be erased!
Thanks again!
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 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.
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
i want to use my PlayerClick(view v) inside a if condition . but it gives me null Exception. it has to retrieve button id.
//Main Code where i wan to call
while (gameLoop > 0){
while(PlayerClick(null) != 1){
if( WinnerCheck(currentUser.getSymbolValue()) == 1 || WinnerCheck(currentUser.getSymbolValue()) == 0 ){
return currentUser;
}
if (gameLoop % 2 == 0)
currentUser = me;
else
currentUser = opponent;
}
gameLoop--;
}
Function Is here
public int PlayerClick(View v) {
//
switch(v.getId()){
case R.id.btnone:
return -1;
case R.id.btntwo:
return -1;
}
return 1;
}
Aim to do this just to pause a while loop while right button is being clicked
im using android:onclick = "PlayerClick" for four buttons in XML
i want to use my PlayerClick(view v) inside a if condition . but it
gives me null Exception.
Because you are passing null to PlayerClick method.
To get it work you should pass Button view which is pressed by user as parameter in PlayerClick method.
findViewById(android.R.id.yourlayout) pass this in PlayerClick()
like
PlayerClick(findViewById(android.R.id.yourlayout))
Do
button.setOnClickListener(this);
Let your activity implement OnClickListener
And when you get onClick(View v) of activity, do as below
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.btn_nativex:
PlayerClick(v);
break;
default:
break;
}
}
public int mPlayerClick;
public void PlayerClick(View v) {
int viewId = v.getId();
if (viewId == R.id.btnone) { mPlayerClick = -1; }
if (viewId == R.id.btntwo) { mPlayerClick = -1; }
else mPlayerClick = 1;
}
And then.
while (gameLoop > 0){
while(mPlayerClick != 1){
...
I don't understand what you are trying to do though, so this might be wrong. This way mPlayerClick will be set to 1 (and stop your loop) only if the user clicks on some button that is not either btnone or btntwo.
Of course all of your buttons need to call PlayerClick() on click.