简体   繁体   中英

Button android while pressed

I want to print something while my button is pressed (not after it is released). At moment I have this, but it only works once...

button.setOnTouchListener(new View.OnTouchListener() {
    public boolean onTouch(View v, MotionEvent event) {
        if(event.getAction() == MotionEvent.ACTION_DOWN) {
            System.out.println("pressed");
            return true;
        }
        return false;
    }
});

try this to continously print pressed message while you are pressing it.

button.setOnTouchListener(new View.OnTouchListener() {
    public boolean onTouch(View v, MotionEvent event) {
            System.out.println("pressed");
            return false;
    }
});

System.out doesn't work in an Android Device (won't show you anything on the device) and if you have a text view you can set the text on your MotionEvent.ACTION_DOWN as you are already doing and on the MotionEvent.ACTION_UP you set your text of your text view to empty. Something like this:

public class TestActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main2);
        final TextView textView = (TextView) findViewById(R.id.textview);
        final Button button = (Button) findViewById(R.id.button);
        button.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if(event.getAction() == MotionEvent.ACTION_DOWN){
                    textView.setText("Button Pressed");
                }
                if(event.getAction() == MotionEvent.ACTION_UP){
                    textView.setText(""); //finger was lifted
                }
                return true;
            }

        });
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM