I am making an android app. Here's what I want: User clicks a button, button text changes to "xyz", and then the program waits for 1 second and then the button text changes to "abc".If I use Thread.sleep(1000) then the program does stop for a second but the button text doesn't change to "xyz" before the program goes to sleep.
You can use Handler to achieve this. Using postdelayed method you can do this. Below is the code to do this
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
button.setText("xyz"); // text changed to xyz
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
button.setText("abc"); //text changed to abc after 1 second.
}
},1000);
}
});
Related
I added the following lines of Code into my OnCreate method.My goal is to assign a button to two functions and to call them up alternately. With the first click the text of the button should be changed and the EditText should be editable. At the second click, the fields should no longer be editable and the button text should change to the first alternative. I have implemented two OnClickListeners and the program structure seems logical to me. Nevertheless, I get an error message; "Cannot resolve symbol onClickListener". What can I do to get the setup described above up and running? Thanks for all responses!
private Button ProfilUpdate;
ProfilUpdate=findViewById(R.id.buttonProfilUpdate);
.
.
.
.
final ProfilUpdate.OnClickListener listener2 = new View.OnClickListener() {
#Override
public void onClick(View v) {
ProfilUpdate.setText("Profil bearbeiten");
profilVorname.setFocusable(false);
}
};
ProfilUpdate.OnClickListener listener1 = new View.OnClickListener() {
#Override
public void onClick(View v) {
ProfilUpdate.setText("Ă„nderungen speichern");
profilVorname.setFocusable(true);
v.setOnClickListener(listener2);
}
};
ProfilUpdate.setOnClickListener(listener1);
why don't you create a boolean isFirstClick = true , and then check it in the same listener
ProfilUpdate.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
if(isFirstClick){
//Do the job for the first click process
isFirstClick= false;
}else {
//Do the job for the second click process
isFirstClick= true;
}
}
};
ProfilUpdate.setOnClickListener(listener);
There can only be one click listener on one view at a time. Use ProfileUpdate.setOnClickListener(listener object). To get the alternate functionality, you can define a Boolean to keep track of the state, for the example, define a class variable at the top Boolean shouldChangeText = true, and in the onClick body in the listener, do something like:
If (shouldChangeText) { // change the text
}
else { // clear the text
}
shouldChangeText = !shouldChangeText
Sorry for the terrible title, I am bad at describing these things.
I am building a metronome and have a (-) UI button that decreases the tempo by 1, and a (+) UI button that increases the tempo by 1.
My problem currently is that whenever I press either buttons, the metronome restarts itself since there's a new tempo, and plays immediately. So if you press the (-) button 10 times in a row, each time you press it you hear the initial metronome "beep".
I would like my app to do the following:
When the user clicks either (-) or (+) buttons, wait for 200 milliseconds
IF the user didn't click the buttons again in that timeframe, play the metronome
If the user DID click the button again, don't play the metronome, repeat the process: wait 200 milliseconds, if no click was made play the metronome, etc
The end result would be that if I'm at 100 bpm and I repeatedly press the (+) button 20 times until I am at 120 bpm, the metronome wouldn't start playing until I am done tapping.
How do I go about implementing this? Thank you!
Declare and instantiate the below in your activity:
private Handler timeoutHandler = new Handler();
private Runnable delayStartThread = new Runnable() {
public void run() {
startMetronome();
}
};
Then insert the below code block in your onClickListener for both + and - buttons:
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
timeoutHandler.removeCallbacks(delayStartThread);
tempoOfMetronome++; //tempoOfMetronome--; for decrease button
stopMetronome();
timeoutHandler.postDelayed(delayStartThread, 200);
}
});
For more details on how the code works, refer the below links for examples (I used these examples to formulate the answer):
Android: clicking TWICE the back button to exit activity - How to use handler.postDelayed()
How to cancel handler.postDelayed? - How to cancel handler.postDelayed()
You should also look at the Android documentation for those methods.
If you want a delay between the action and the effect, there are several ways you can achieve it. This is one.
private boolean pressedAction = false;
#override
public void onClick(View v) {
if (pressedAction) return;
pressedAction = true;
new Thread(new Runnable(
#override
public void run() {
try {
Thread.sleep(200); // 200 miliseconds
} catch (Exception e) {}
// Update views or do work (program logic)
pressedAction = false;
}
}
}
Then, the metronome logic is your bussiness.
I need to perform an action after onClick method of OnClickListener has run.
Here is my code for onClickListener:
View.OnClickListener imgButton0Handler0 = new View.OnClickListener() {
int identifier=0;
public void onClick(View v) {
//check if tile is found and return if it is
if(isFound[identifier]==true) return;
//set tile as open
checkField[identifier]=1;
//set background on predetermined
button0.setBackgroundResource(tiles[identifier]);
}
};
After this has run, and the background is set I would like to call a method checker(int identifier) which will check for other open tiles and change backgrounds accordingly.
This method needs to be run separately because the background is only displayed after onClick finishes, and I need predetermined background shown for a short time before checker method changes it to something else.
How can I accomplish this?
Have You Tried Post Delayed see this,
View.OnClickListener imgButton0Handler0 = new View.OnClickListener() {
int identifier=0;
public void onClick(View v) {
//check if tile is found and return if it is
if(isFound[identifier]==true) return;
//set tile as open
checkField[identifier]=1;
//set background on predetermined
button0.setBackgroundResource(tiles[identifier]);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// This method will be executed once the timer is over
// Start your app main activity
checker(identifier) // your method call
}
}, 3000); // 3 second
}
};
I want to know how can I stop message sending in a loop.
When I press stop, messages are still sent.
I have provided a stop() method.
for (i = 0; i < copy; i++) {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
if(stop!=1)
sms.sendTextMessage(number,null,message,sentPIn,pdelint);
}
}, 25000);
stop method
int stop=0;
public void st(View view){
Button b=(Button)findViewById(R.id.button2);
b.setText("Stopped");
stop=1;
}
Modify St function to this
public void st() {
Button b = (Button) findViewById(R.id.button);
#Override
b.setOnClickListener(new View.OnClickListener() {
b.setText("Stopped!");
stop=1;
});
}
The problem was u were not using an listener to detect button press. It is not advisable to change the button text use a text view instead!
Most likely he has set onClick attribute in the xml, although only he'll be able to clarify that.
I'm saying that because I see View as a parameter in the method st(View v).
Although if the attribute onClick is not set in xml #Audi 's solution would be good. Though on the contrary if the attribute has been set in the xml then
you should check if view.getId() == R.id.button then apply a button cast to your view and set its text to "Stopped".
I am developing a board game that user plays with android. Since android is quite fast, I want to fake that android is performing some tough calculations and thus needs time for its next move.
What I want to do:-
User turn - he moves.
Android turn - android shows text "I am thinking" for 2 seconds
Android hides that text and and only after that moves his turn.
I tried doing:-
onAndroidTurn(){
textView1.setVisibility(View.VISIBLE);
Thread.sleep(2000);
textView2.setVisibility(View.GONE);
}
But what happens is that thread sleeps but text is not shown (okay I know why).
Then searching on stackoverflow, I learnt a way:-
onAndroidTurn(){
textView1.setVisibility(View.VISIBLE);
new Handler().postDelayed(new Runnable(){
void run() {
textView1.setVisibility(View.GONE);
}
}, 2000);
}
Now what this does is that it runs that text in another thread and android's turn is updated on screen and after moving it's turn android showing "Thinking" is total stupidity.
What can I do for this?
Try the following:
Show "I'm thinking"
Calculate your move but don't actually do the move, just store it for a while
Schedule timer
When timer runs out remove the text and do the move
Something like this:
onAndroidTurn(){
textView1.setVisibility(View.VISIBLE);
saveMove(calculateNextMove());
new Handler().postDelayed(new Runnable(){
void run() {
textView1.setVisibility(View.GONE);
doNextMove(restoreMove());
}
}, 2000);
}
Maybe you could just use an AsyncTask (like this pseudo-code):
private class ShowTextTask extends AsyncTask<Void, Void, Void> {
protected void onPreExecute(Void... result) {
textView.setText("Initital");
}
protected Long doInBackground(Void... urls) {
Thread.sleep(2000);
}
protected void onPostExecute(Void... result) {
textView.setText("After 2 seconds");;
}
}
Okay i did it like this:-
public void androidThinking(){
textView1.setVisibility(View.VISIBLE);
androidThinking = true; //explained below
new Handler().postDelayed(new Runnable(){
#Override
public void run() {
droidThink.setVisibility(View.GONE);
//CODE for android's turn
androidThinking = false; //explained below
}
}, 2000);
androidThinking when set to true prevents the user from moving his turn by forcing the listener for user's button to return prematurely
btn.setOnClickListener(new View.onClickListener(){
#Override
public void onClick(View v) {
if(androidThinking)
return;
Thanx everyone for your reply.