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.
}
});
Related
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;
}
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~
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
}
I'm in a situation where I have four radiobutton, next button and one question. now my issue is that if the user clicks next button without selecting any option it should show a toast message and if user clicks any one of the radio button, it should be checked whether it is right or wrong. I have partially implemented but I cant get the exact solution. any one help me with this.
Thanks in advance
I have posted my code below
Next.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
count++;
if(viewFlipper.getDisplayedChild()==0)
{
id1 = rag1.getCheckedRadioButtonId();
rab1=(RadioButton)findViewById(id1);
//System.out.println("1nd question answer"+rab1.getText());
if (rag1.getCheckedRadioButtonId()!=R.id.btn1_1||rag1.getCheckedRadioButtonId()!=R.id.btn1_2||rag1.getCheckedRadioButtonId()!=R.id.btn1_3||rag1.getCheckedRadioButtonId()!=R.id.btn1_4||rag1.getCheckedRadioButtonId()!=R.id.btn1_5&&rag1.getCheckedRadioButtonId()==-1)
{
Toast.makeText(getApplicationContext(), "Please enter the answer", Toast.LENGTH_SHORT).show();
}
if((rag1.getCheckedRadioButtonId()!=-1)&&rab1.getText().equals(c_alcorrectanswer.get(0)))
{
System.out.println("1nd question answer"+rab1.getText());
}
else
{
Toast.makeText(getApplicationContext(), "Please enter the correct answer", Toast.LENGTH_SHORT).show();
viewFlipper.stopFlipping();
}
}
You should check within one condition only. Whether any of your RadioButton of your RadioGroup is selected or not.
int radioButtonID = radioButtonGroup.getCheckedRadioButtonId();
if(radioButtonID > 0) //return -1 if none of radiobutton is selected from radiogroup
{
//move to next
}
else
{
// show toast. Please select any option.
}
As per your code snippet:
if(viewFlipper.getDisplayedChild()==0)
{
id1 = rag1.getCheckedRadioButtonId();
if(id1 < 0) //return -1 if none of radio button is selected
{
//Toast. Please select any answer
}
}
developer.android.com documentation reference
I have an app with a lot of buttons (more than 300)
i want to know if there is a way to use android:onClick="function" with an arguments in my layout xml
because im too lazy to make a function for each button, and i want to do somenthin like
public void allbuttons(View view, String stringa) {
if stringa = 1 { bla bla bla}
elif stringa = 2 { blachos}
}
you get the idea
Give an id to each of your button.
In your common handler, just check the ((Button)view).getId() for the id in a switch (with the latest adk, you have to use if-else) and handle it differently in each case.
public class MyButtonClickHandler implements View.OnClickListener {
#Override
public void onClick(View v) {
Button button = (Button) v;
if (button.getId() == R.id.button1) {
Toast.makeText(Sample1Activity.this, "Toast1", 1000).show();
} else if (button.getId() == R.id.button2) {
Toast.makeText(Sample1Activity.this, "Toast2", 1000).show();
}
}
}
and in your onCreate of activities you can add
Button button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new MyButtonClickHandler());
I am adding function reference in the code but you can do it in xml file too.