Condition On Button click - android

When the button is clicked it should show me some text. This is working. Whenever the limit on the button click is exceeded, it must show some user defined text. After clicking the button 3 times, it is showing me some text not the user defined one. Here is my code for the OnClickListener:
final Button btnca =(Button) findViewById(R.id.btnca);
btnca.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int c=1;
if(c <= 3) //if button click for first three times
{
new FancyShowCaseView.Builder(Playing.this)
.title(questionPlay.get(index).getCorrectAnswer())
.build()
.show();
score -= 10;
txtScore.setText(String.format("%d", score));
c++;
}
if(c>3) //if button click for after three times
{
new FancyShowCaseView.Builder(Playing.this)
.title("Your Limit Exceed")
.build()
.show();
}}
});

The problem is that c is local to the onClick method so it is starting at 1 for every click. Try moving it out to the class level
final Button btnca =(Button) findViewById(R.id.btnca);
btnca.setOnClickListener(new View.OnClickListener() {
int c=1; //initialize here so it's re-used in each onClick
#Override
public void onClick(View v) {
if(c <= 3) //if button click for first three times
{
new FancyShowCaseView.Builder(Playing.this)
.title(questionPlay.get(index).getCorrectAnswer())
.build()
.show();
score -= 10;
txtScore.setText(String.format("%d", score));
c++;
}
if(c>3) //if button click for after three times
{
new FancyShowCaseView.Builder(Playing.this)
.title("Your Limit Exceed")
.build()
.show();
}}
});
Edit: I should mention this isn't a complete solution. I'll assume this code is in Activity(or Fragment).onCreate(). The counter will reset on configuration change when your lifecycle component is re-created, but I'll leave that solution as an exercise for the reader :)

You should initialize counter variable c outside of onClick() method. Of-course you should initialize it as c = 0 instead of c = 1 to get the toast after 4th click.
Try this:
final Button btnca =(Button) findViewById(R.id.btnca);
btnca.setOnClickListener(new View.OnClickListener() {
int c = 0;
#Override
public void onClick(View v) {
if(c <= 3) //if button click for first three times
{
new FancyShowCaseView.Builder(Playing.this)
.title(questionPlay.get(index).getCorrectAnswer())
.build()
.show();
score -= 10;
txtScore.setText(String.format("%d", score));
c++;
}
if(c>3) //if button click for after three times
{
new FancyShowCaseView.Builder(Playing.this)
.title("Your Limit Exceed")
.build()
.show();
// Reset if required
//c = 0;
}}
});
FYI, if you want to reset variable c, then reset(c = 0) it inside your condition if(c>3).
Hope this will help~

Related

Android: Button's onClick Method not processed linearly?

I'm learning Android app coding and thought it would be a nice idea to code TicTacToe. So I got me six buttons aligned linearly in one activity, which change their color when clicked on, depending on the player's turn (orange or blue). The onClickListener's onClick method goes as follows:
public void onClick(View v)
{
if(player == 1)
{
((Button)v).setBackgroundColor(getResources().getColor(android.R.color.holo_orange_dark));
}
else
{
((Button)v).setBackgroundColor(getResources().getColor(android.R.color.holo_blue_light));
}
gameControl();
}
gameControl follows with the game basics: Check if a player won, if it is a draw or not etc.:
public void gameControl()
if(checkForWin())
{
playerWins(player);
}
else if(round == 9)
{
draw();
}
else
{
if(player == 1)
player = 2;
else
player = 1;
}
round++;
}
My problem is that if a player won, that is if the last button to win the game is clicked, the button's color won't change. Rather, the playerWins method (in gameControl) refreshes the "playfield" before the button's color changes. I've tried stuff like Handler.postDelayed and such because it seems like the entire onClick methods is run through before the button's color is addressed, but no success there. Why is the onClick method not processed linearly? Is there any way to refresh the activity or something? Thanks in advance ...
Thanks for the quick response, here are the requested methods:
private void playerWins(int player)
{
if(player == 1)
{
player1Points++;
Toast.makeText(this,"Player 1 wins!", Toast.LENGTH_SHORT).show();
updatePointsText();
resetBoard();
round = 1;
}
if(player == 2)
{
player2Points++;
Toast.makeText(this,"Player 2 wins!", Toast.LENGTH_SHORT).show();
updatePointsText();
resetBoard();
round = 1;
}
}
The resetBoard method:
private void resetBoard()
{
for(int i = 0; i < 3; i++)
{
for(int j = 0; j < 3; j++)
{
buttons[i][j].setBackgroundColor(Color.parseColor("#B0C4DE"));
}
}
}
Yes, it is happening to quickly i guess and that's why you are not seeing it. You have a some approaches:
1- Putting a refresh button somewhere and only refresh when it is clicked (This option would be good for example if users know it will be a draw and they want to start again before finishing). So with this option you will not reset before user see the update.
2- Showing an AlertDialog to say "Player X wins!" and when user press OK you reset the board. It would be something like
AlertDialog dialog = AlertDialog.Builder(context);
dialog.setTitle("Your title");
dialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
resetBoard()
}
});
dialog.setCancellable(false);
dialog.show();
Also just check you can reduce some code refactoring, as you are repeating code. For example playerWins() could be
private void playerWins(int player){
if(player == 1)
{
player1Points++;
Toast.makeText(this,"Player 1 wins!", Toast.LENGTH_SHORT).show();
}
if(player == 2)
{
player2Points++;
Toast.makeText(this,"Player 2 wins!", Toast.LENGTH_SHORT).show();
}
updatePointsText();
resetBoard();
round = 1;
}

how do u add multiple fixed int from four buttons to an array

edit.
I'm trying to make a game where there is 4 buttons each button has a set value.
buttone is 1 buttontwo is 2 and so on.
and on each click of the button it takes the value from what ever button is pressed and add it to an array, the number of buttons that you have to press is set by the intent from the main activity and the buttons that have to be press is set by the randomNums array.
eg.
if the randomNums give you 1,2,1,1,2.3,3,4.
green button must be pressed 3 times
blue button must be pressed 2 times
yellow button must be pressed once.
buttonOne must be pressed 3 times.
buttonTwo must be pressed 2 times.
buttonThree must be pressed 2 times.
buttonFour must be pressed once times.
I have the randomNums which gives you the up to 12 number from 1-4.
I have the buttons set up so that if the randomNums gives you 1,1,1,2,3,3.
ButtonOne will be green buttonTwo will be yellow and buttonThree will be blue
for 3 seconds then all the buttons turn grey.
but where I'm having trouble is how do u set a button to have a set value.
eg.
if I press buttonOne 3 times it will enter into an array like so 1,1,1.
so the question is how do set a fixed value to a button so that every time it is press it send a fix value to an array.
sry if I was not clear the 1st times around if u have any more question or if you need me to explain it again or want to see the code that I have to set the color of the button play let me know . thanks
hi I'm very new to android studio,
I have 4 buttons and I want each to have a fixed value.
ButtonOne =1;
ButtonTwo =2;
ButtonThree =3;
ButtonFour =4;
and when a button is pressed I want to add that fixed button value to an array.
what I have is sending an ++ number back and not sending a fixed value.
so my question is how do you send a multiple fixed int from four buttons OnClickListener to an array?
public int counterOne = 0;
final Button buttons[] = {
(Button) findViewById(R.id.ButtonOne),
(Button) findViewById(R.id.ButtonTwo),
(Button) findViewById(R.id.ButtonThree),
(Button) findViewById(R.id.ButtonFour)
};
buttons[0].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
counterOne = counterOne+1;
CheckSET.setText(""+counterOne);
}
});
final int pressed[] =new int [12];
end.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String stringlevel = ""+CheckSET.getText();
String b = "";
final int intLevel = Integer.parseInt(stringlevel);
for (int i = 0; i < 12;i++){
//b = ""+ b +""+ pressed[i];
//pressed[i] = pressed[i]+1;
//if(intLevel==1){
// pressed[i] = pressed[i]+1;
//}else if (intLevel ==2){
// pressed[i] = pressed[i]+2;
//}
pressed[0] = counterOne;
b = ""+ b +""+ pressed[i];
diff.setText(b);
}
}
});
the end button is to add all the button clicks to the array.
but if there is a better way then doing an end button to run the button array that would be great. could you do a for() and have all the buttons inside the for and each time they are pressed it adds it to the array?
I have a random array set up all ready that picks 12 numbers from 1-4 and does not let any number repeat more then 3 times.
private int[] pickNums() {
Random rand = new Random();
int randomNums[] = new int[12];
int one = 0;
int two = 0;
int three = 0;
int four = 0;
for (int i = 0; i < 12; i++) {
randomNums[i] = rand.nextInt(4)+1;
if (randomNums[i] == 1) {
one = one + 1;
if (one>3){
i=i-1;
}
} else if (randomNums[i] == 2) {
two = two + 1;
if (two>3){
i=i-1;
}
} else if (randomNums[i] == 3) {
three = three + 1;
if (three>3){
i=i-1;
}
} else if (randomNums[i] == 4) {
four = four + 1;
if (four>3){
i=i-1;
}
}
}
return randomNums;
}
my plan is to do a bubble sort on the randomNums and on the buttonPress array to see if the buttons that are pressed all ==.
but I'm having a lot of trouble with the buttonpress array
I am not sure what you asking but may be this will help you
(Instead of Array you should use list)
private List<Integer> pressedNums = new ArrayList<>();
Button button1,button2,button3,button4;
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pressedNums.add(1)
}
});
similarly for button2,3,4 add 2,3,4
at last you can use loop
int total = 0;
for(Integer i : pressedNums){
total += i;
}
textField.setText(Integer.toString(total));

How to set multiple click action in a imageview and plus, minus button increment and decrement in android

Hlw,
Problem1:
I am developing a app where I have a ImageView like favorite button where I click and change this image resource(it is done), but I want to set action when user again click this imageview and the image remain same.
Problem2:
I have two image button "plus" and "minus" I set condition to it that when user click + button middle textview increment by 1, and when it reach 10 then the button will unclickable, also for the minus button, when textviw equal=0 then it not works...
I done it by condition but when minus button reach 0 and after plus button click, it increment but not decrement it remain unclickable...
how can i solve this problem?
Image like this
productWrapper.plus.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Toast.makeText(context, "Plus", Toast.LENGTH_SHORT).show();
try
{
String presentValStr= finalProductWrapper2.selectedQuantity.getText().toString();
int presentIntVal=Integer.parseInt(presentValStr);
presentIntVal++;
if (presentIntVal>=10){
Toast.makeText(context,"You can select max 10 product",Toast.LENGTH_LONG).show();
finalProductWrapper2.plus.setEnabled(false);
}
finalProductWrapper2.selectedQuantity.setText(String.valueOf(presentIntVal));
}
catch(Exception e)
{
e.printStackTrace();
Toast.makeText(context,"Error! please try again",Toast.LENGTH_LONG).show();
}
}
});
final ProductWrapper finalProductWrapper = productWrapper;
productWrapper.heart.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
finalProductWrapper.heart.setImageResource(R.drawable.heart2);
}
});
Point #1.
You can use boolean flag like below
if(flag == true){
flag = false;
// Change your Image Resource here
}
else {
flag = true;
// Do your other action
}
for Minus button put following condition
if(YOUR_POINTS >0){
// Do your action
}
else {
// Ignore
}

Adding point to score

I'm working on a school project in Android Studio (a small game) and I now want to implement scores.
So here is the code where I want to implement the score:
private int score = 0;
final View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
if(v.equals(buttonBigger) && doubleResult1 > doubleResult2) {
Log.v("TAG", "you are right");
// Add 1 point to score
generatorEasy1();
generatorEasy2();
}
else {
Log.v("TAG", "you are wrong");
goToEndscreen(); // Go to Endacreen when wrong
}
}
};
So whenever you pressed the right button I want to add 1 point to the score. I've tried the following:
if(v.equals(buttonBigger) && doubleResult1 > doubleResult2) {
Log.v("TAG", "you are right");
score += 1;
textScore.setText("Score : " + score);
}
The problem is that if I run the app and I press the right button, the score stays 0.
I don't know what I'm doing wrong so it would be nice if someone could help me.
Not sure what you are trying to do with this game. But, you can set an on click listener directly on the buttons that are to be clicked. No need to add an if statement to check which view is initiating the listener.
biggerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Whatever you want to do when the
// button is clicked in here.
}
});

changing images on button click

I have 3 images in my app. The images are numbers. The maximum number displayed on all the 3 images will be 9. At first the image in the unit's place will be 1 and the rest images will be 0. On Clicking on the "next" button, the next number is being displayed i.e. 2. Proceeding in this way till the last number 9,then on the next click the unit's place becomes 0 and the ten's place becomes 1 and so on will proceed till 999. There is a previous button too which will reverse the condition of next button and will decrement the numbers by one digit. I am able to achieve the next button condition by using if else conditions but unable to do the same for previous button. please help.
int image1 = 2;
int image10 = 0;
int image100 = 0;
int max = 10;
final int [] images = {
R.drawable.num00,R.drawable.num_0, R.drawable.num1, R.drawable.num2, R.drawable.num3, R.drawable.num4,
R.drawable.num5, R.drawable.num6, R.drawable.num7, R.drawable.num8, R.drawable.num9
};
ImageButton next = (ImageButton)findViewById(R.id.imageButton1);
next.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if((image1==max)&&(image10<max)) //for value with 9, 19... to increment
{
image1=1;
if (image10==0)
{
image10=2;
}
else
{
image10++;
}
img1.setImageResource(images[image1]);
img2.setImageResource(images[image10]);
}
else if((image1==max)&&(image10==max)&&(image100>=0)&&(image100<=10)) //for value with 9 in 1st block to increment
{
image1=1;
image10=1;
if (image100==0)
{
image100=2;
}
else
{
image100++;
}
img1.setImageResource(images[image1]);
img2.setImageResource(images[image10]);
img3.setImageResource(images[image100]);
}
else if (image100<=10) //for value below 9 in 1st block to increment
{
image1++;
img1.setImageResource(images[image1]);
}
}
});
Here, image1 is the position of image in the unit's place, image10 in the ten's place and image100 in the hundred's place.
The implementation can be optimized a lot.
Why cant you go for a simple number like below.
int number = 0;
for next button:
if(number <1000){
number++
updateImages()
}
for previous button:
if(number > 0){
number--
updateImages()
}
After doing the above line for those prev/next buttons, simply write a method like below.
updateImages(){
unitsPlace = number%10;
tensPlace = ((number/10)%10);
hundredsPlace = ((number/100)%10);
img1.setImageResource(images[hundredsPlace]);
img2.setImageResource(images[tensPlace]);
img3.setImageResource(images[unitsPlace]);
}
Thats it.

Categories

Resources