I need the Button to change the layout when I hold it down for 3 seconds, but when I push once quickly it should just play a sound.
In the code below the sound comes no matter what (because that’s okay in this case).
My problem is that it only changes page the very first time you use the Button whether it’s held down (to change layout) or just a short click (only to play sound).
So if I hold down button and it changes layout, but then I go back it won’t work a second time. Also, if a short touch is used to play the sound I can’t hold the button down to change layout.
final Button b1pad1 = (Button) findViewById(R.id.b1pad1);
b1pad1.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, final MotionEvent event) {
// TODO Auto-generated method stub
switch(event.getAction()) {
case MotionEvent.ACTION_DOWN:
MediaPlayer mp = MediaPlayer.create(PhotosActivity.this, R.raw.sub);
mp.start();
holdTimer = new Thread() {
public void run() {
try {
int timer = 0;
while (timer<3000) {
sleep(100);
if (event.getAction() == MotionEvent.ACTION_UP) {
//checks whether you lifted your finger before
//the 3 seconds.
breaked = "no";
//"no" means "don't change layout"
changetobrowser(b1pad1, breaked);
break;
}
timer = timer + 100;
}
if (breaked.equals("")){
breaked = "go"; //go means "change the layout"
changetobrowser(b1pad1,breaked);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
holdTimer.start();
break;
case MotionEvent.ACTION_UP:
// End
break;
}
return false;
}
});
public void changetobrowser(Button but, String breaked) {
if (breaked.equals("go")){
Intent browseIntent = new Intent(PhotosActivity.this, BrowseScreen.class);
startActivity(browseIntent);
} else {
}
}
What could the problem be? And is this even the easiest way to do it?
Have you considered using an
OnLongClickListener? It’s invoked when aViewhas been clicked and held for a short while. For other cases, you can use a simpleOnClickListener, which is invoked upon press.More information here: http://developer.android.com/reference/android/view/View.OnLongClickListener.html