简体   繁体   中英

how can i detect when a button is clicked but not released in android

我正在寻找一种方法来找出如何在单击但未松开按钮时通过使用Java代码来更改android中按钮的颜色,很高兴能得到帮助。

button.setOnTouchListener(new View.OnTouchListener() {

    public void onTouch(View view, MotionEvent e) {
        switch(e.getAction()) {
            case MotionEvent.ACTION_DOWN:
                System.out.println(" mouse pressed ");
                break;
            case MotionEvent.ACTION_UP:
                System.out.println(" mouse released");
                break;
        }

    }
});

you can use MotionEvent.ACTION_DOWN case to handle your button color change logic.

hope this will be help to you

if you got it inform me :)

Check out the documentation at Android Documentation . It shows that button has different states and you can align color on each state. Also check this link

You can use the selector for that like below code

Create selet.xml in drawable

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Selector style for listrow -->
<item 
 android:state_selected="false"
    android:state_pressed="false" 
    android:drawable="@drawable/gradient_bg" />
<item android:state_pressed="true" 
    android:drawable="@drawable/gradient_bg_hover" />
<item android:state_selected="true"
 android:state_pressed="false" 
    android:drawable="@drawable/gradient_bg_hover" />
</selector>

Now set the background of button like below

 <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
       android:background="@drawable/selector" />

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