Check if a button is pressed and then check again - android

I am rather new to android developing and can't figure out how to do a double check on a button press.
I am working in Android Studio and am trying to create a little simple game and have the following: two buttons (button1 and button2)declared and instantiated in an onClick method.
When button 1 is pressed a counter is incremented and a specific value is shown on the button from an array with the values 0, 10, 50, 100.
This part works like a charm. What I can't do is create a working "tiebreaker rule" which should be something like:
if (button1 value == 100 and button2 value == 100) or this can be done with the counter if (counter1 == 3 && counter2 == 3)
tiebreaker();
this is what I need to do:
public void tiebreaker(){
if (button1 is pressed){
button1.setText(String.valueOf("OK. One more!");
if (button1 is pressed (again){
resetCounters();
goForPlayer1(); //distinct method
} else if (button2 is pressed) {
//set both values back to 100
tiebreaker(); //calls itself in order to repeat until a button is pressed twice consecutivelly
} (else?)
if(button2 is presed){
//same code as above, just with the numbers 1 and 2 swapped
}
}
I have tried implementing this tiebreaker method in different ways, but with no final success. I tried with if(button1.isPressed()) as condintion, having a boolean turn true when the button is pressed and using it as a condition, using the values from the buttons with button.equals("100") or whatever should be written but nothing.
Also, I tried making the tiebreaker as a second onClick method and doing checks based on switch (View.getId()) but the problem here is that the method being view dependant (tiebreaker(View v)) I am not sure how to call it from a different method.
IMO the main issue is that if within another if or switch/case within another switch/case can't be used when it comes to button presses (I could be wrong, though), but I don't know of any other way to do this.
I hope I did not miss anything and managed to make myself clear.
I appreciate any input in helping me solve this tiebreaker rule. Thank you

it's probably something like this ...
whenButtonAIsPressed() {
do some stuff
possiblyRunTiebreakerMaterial()
}
whenButtonBIsPressed() {
do some stuff
possiblyRunTiebreakerMaterial()
}
Note that you always run possiblyRunTiebreakerMaterial() and you always run it at the end of doing all your other processing.
Here's the nature of your possiblyRunTiebreakerMaterial() function...
possiblyRunTiebreakerMaterial() {
// there are some conditions, which mean you DO want
// to run the tie breaker:
do some processing, such as
value of A = blah blah
value of B = blah blah
// now have a boolean, and figure it out
boolean shouldWeRunTheTieBreaker
processing
processing
shouldWeRunTheTieBreaker = blah
and now finally:
is shouldWeRunTheTieBreaker == true { tiebreaker() }
}
and then have your tiebreaker() function.
What you're really looking for is a state machine, but don't worry about that for now.
The general "programming trick" you're looking for here is that you must do these things:
always do your processing
then, only afterwards,
in all cases, check IF you need to run the tiebreaker
run it if needed
That's the pattern.

Unfortunately, I don't have the rating to upvote.
I managed to resolve the issue. Instead of a function, I created a boolean for tiebreaker and it looks something like:
if (p1 = 100 || p2 == 100)
tiebreak = true;
if (p1 == 100 && tiebreaker){
p1 == OK;
tiebreaker = false;
} else //same thing for p2

Related

Checking if two objects have the same y-axis

I have been creating a simple android game, but have been encountering some problems in checking if an object falling down has passed another object on the y-axis.
This is my code:
//SKULLY is the object falling down
//USER is the object that SKULLY will have to pass through to add a point
public void checkPassed()
{
if (skullY == user.getY())
{
scoreCount++;
txtScore.setText("SCORE: " + String.valueOf(scoreCount));
}
}
What I am trying to do is that, when SKULLY passes through or is equal to the y-axis of the USER then it will add a single point.
When I change the condition to > or < it works perfectly fine no matter what position USER is in. But when I put it in ==== no point is added.
If you have to downvote me, please leave a comment on why was I downvoted. Thanks in advance for any help or insight on this problem! :D
since its sound like a Game equals ("==") almost never happens.. my Suggestion is
if(skullY < user.getY() && skullY > user.getY() + 10) {
// Do Stuff here..
}
try to lower 10 as much as possible until you will get the desire result..

Catching the Back key on Android with an Inputmultiplexer

ive got another Question for you.
So im trying to get the user input working on an options menu. For this i got:
1. The Stage and
2. An extra Inputadapter
I need the extra Inputadapter to catch the BACK key on Android. So i have used an Inputmultiflexer, which allows me to use both inputprocessors.
InputMultiplexer multiplexer = new InputMultiplexer();
multiplexer.addProcessor(this);
multiplexer.addProcessor(stage);
Gdx.input.setInputProcessor(multiplexer);
Gdx.input.setCatchBackKey(true);
And my method to check for the BACK button looks like this:
#Override
public boolean keyUp(int keycode){
if(keycode == Input.Keys.ESCAPE || keycode == Input.Keys.BACK){
new MenuScreen(game);
return true;
}
return false;
}
The problem: Its not working at all. It does not go back, when using the Back key on Android or the Escape key on Desktop. The only thing the Console is printing out when pressing the Button is :
Load KCM of non-default device may incur unexpected result
To be honest, i have no idea what its means and Google didnt help me either with that.
So how do i get this to work?
First when debugging, you should use something like :
System.out.println("back was pressed");
If you see that output in the console then you know input is working. If that works, the only problem I see with your code is that you may have created a new screen class, you never made it switch screens. I noticed you passed in the game object, so you should probably have something like this:
game.setScreen(new MenuScreen(game));
Hope this helps.

Detect soft keyboard closing by use of nav bar close button

I've spent most of the day searching and trying various solutions and while I've come most of the way, I'm cursed by the "close" (maybe it has more appropriate name, idk) button on the nav bar when the keyboard is displayed (as in the attached image.)
I have a few editTexts which allow the user to adjust some parameters before a graph is recomputed and redrawn. I need to know when their input is complete. I've managed to sort out the "Done" button but for the life of me I can't figure out how to handle hitting that close button. I've also adapted some code which determines if the keyboard was opened and then closed (which is the case with these editTexts) but it only works when using the Done button (so is somewhat redundant).
So.. is there some way of picking up when the user has closed the keyboard using the nav bar?
TIA
Well, I think I have something here, perhaps it will be useful to others. Who knows how long it will work properly.
So prelude: I needed to be able to tell when a user had completed changing an edit text so that I could then redo a computation and update a graph. I really have no room for an "update" button and felt from a UI standpoint it would have quickly become annoying.
Codewise:
I have a "display" method with an inner "watcher" class with a watch() method. The watcher class has many things, including the various editTexts which watch()..watches. I ddapted some code I found here, which determines if the keyboard is open or closed. currentView is the root view of the graphing activity.
currentView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
// TODO Auto-generated method stub
Rect r = new Rect();
getWindow().getDecorView().getWindowVisibleDisplayFrame(r);
int screenHeight = getWindow().getDecorView().getRootView().getHeight();
int heightDifference = screenHeight - (r.bottom - r.top);
if (MainActivity.debug) Log.d("Keyboard Size", "Size: " + heightDifference+" screenHeight: "+screenHeight);
boolean keyboardVisible = heightDifference > (screenHeight / 3);
if (keyboardToggle) { // someone has updated one of the editTexts
if(!keyboardVisible) { // and they have closed the soft keyboard so are done
// do something
if(MainActivity.debug) {
if(rIDchangedET == firstET.getId()) Log.i(TAG,"update the first thing");
if(rIDchangedET == secondET.getId()) Log.i(TAG,"update the second thing");
if(rIDchangedET == thirdET.getId()) Log.i(TAG,"update the third thing");
}
// reset the keyboard toggle
keyboardToggle = false;
}
}
}
});
This helps but in a somewhat backward way. Knowing open/closed by itself is not useful within any of the text watchers as those are not triggered by the act of closing the keyboard (so you can't actually test for it within the listener)
However, thinking about it a bit I added a boolean keyboard toggle which is set to true in the afterTextChanged of the addTextChangedListener. In addition, I put the rID of that editText in another class variable.
The code which checks the keyboard status then calls the appropriate updating procedure if the a) keyboard is closed b) some text has actually been changed (keyboard toggle) and c) uses the rID to determine what procedure to then call.
I know its a bit convoluted, but it does seem to work.

How can I wait for button click in android?

I'm about to finish my Simon Says game, but I still have one crucial problem.
After my buttons are shown to the player, I have to wait (according to the level, e.g, if 5 buttons were showed to the user, I have to wait the user to click 5 buttons). I have searched around the internet, but the only answer was "You cannot freeze the android Application... blah blah blah".
Here it is my code:
public boolean playerTurn(){
//Enable buttons
buttonUp.setClickable(true);
buttonDown.setClickable(true);
buttonRight.setClickable(true);
buttonLeft.setClickable(true);
/*
Wait for a button clicks depends on the level, but HOW?
e.g, if the level is 5, I have to wait for 5 button clicks
and after it, I can continue to run the code
*/
/*Check if the user typed the correct order
*If pressed the correct order
*return true;
*else
*return false
*/
}
For each button do something like this:
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
buttonsPressedCount++;
if (buttonsPressedCount >= 5) {
// Do whatever you wanted to do
}
}
});
In this way, each button will listen for clicks and update a global counter. Finally when your global counter is greater than 5, you can proceed. The application is never "paused", it just only moves on the next section when five buttons have been clicked.
I'm not near a computer so no code example (will post later). Basically, you can set a class level counter. Provide an OnClickListener for each button - can be same or different. In the listener increment the counter and check if it reached 5 or not. If it did, check the pattern and clear counter.
You can use RxBindings for this purpose. Convert the clicks into a stream of events, and add a subscriber to it, which will react to the event of a click.
Here's how you can do it,
RxView.clicks(button)
.take(5)
.subscribe(aVoid ->
{
// Do your stuff
});
This will add a subscriber to the click event, and will only take the first five events.
Hope it helps.

Android disable button with case differentiation

So I really have no clue why this isn't wokring - basic stuff I did hundred times before:
I want to disable the button 'loadGame' by doing the following if the boolean is false:
if(saveExists == false){
loadGame.setEnabled(false);
}else{
loadGame.setEnabled(true);
}
saveExists is a boolean taken from a sharedPreferences object which is by default false (works, because I already checked saveExists in an output line).
Basically no matter what cases I create with if/elseif/else the button doesn't seem to get disabled at any point - did I really miss something big?
Okay so here's some code concerning the SharedPreference:
SharedPreferences settings;
SharedPreferences.Editor preferenceEditor;
...
In the onCreate of the class where I want to disable the button:
Resource.settings = getSharedPreferences(Resource.PREFERENCE_AUDIO, MODE_PRIVATE);
Resource.preferenceEditor = Resource.settings.edit();
saveExists = Resource.settings.getBoolean("settings", false);
Log.d(TAG, "saveExists="+saveExists);
and finally, the part to disable the Button:
loadGame = (ImageButton) findViewById(R.id.loadButton);
loadGame.setEnabled(saveExists);
loadGame.setOnClickListener(new OnClickListener() {...}
Oh btw we're talking about a ImageButton here
SOLUTION: You won't see this coming
God I hate to break it to you but that was clearly my fault. My projectpartner toggled the buttons invisible/visible as part of the AsyncTask and it's executed after I'm doing what I tried here all the time - yup shame on me I guess :x
It's very hard to determine the problem without more information. If the is/elseif/else doesn't seem to be working, you can try modifying your code to this to see what's going on:
if(saveExists == false){
Log.v("TEST", "saveExists is false");
}else{
Log.v("TEST", "saveExists is true");
}
If that is working then the problem seems to be with disabling the button. Does execution this line without the if/else work?
loadGame.setEnabled(false);
EDIT
From your update, I see you're using an ImageButton. For disabling an ImageButton, use setClickable(saveExists)
why don't use saveExist itself into the argument no need to used if/else
loadGame.setEnabled(saveExists);
if it is true then it is enabled otherwise not

Categories

Resources