繁体   English   中英

使用选择器xml按下的android更改ImageButton的图像

[英]android change image of ImageButton on pressed with selector xml

我在Android中有一个ImageButton ,需要在按下按钮时更改图像,以便用户清楚按下按钮。

我试过的是在我的图像所在的drawable文件夹中使用带有选择器的xml。我的代码如下:

XML

<ImageButton
    android:id="@+id/upButton"
    android:layout_width="0dp"
    android:layout_weight="1"
    android:layout_height="wrap_content"
    android:adjustViewBounds="true"
    android:scaleType="fitXY"
    android:src="@drawable/up_button"
    android:background="#00000000"/>

up_button.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@drawable/up_pressed"
        android:state_pressed="true"/>
    <item android:drawable="@drawable/up"/>

</selector>

java onTouchListener

按下按钮时会更改textView的文本,并在释放按钮时将其更改回来。

upButton.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            switch (motionEvent.getAction()){
                case MotionEvent.ACTION_DOWN:
                    textView.setText("Up button pressed.");
                    break;
                case MotionEvent.ACTION_UP:
                    textView.setText("Up button released.");
                    break;
            }
            return true;
        }
    });

当在这个网站上搜索类似的问题时,我发现按下了Android按钮 ,但这不是很有帮助,因为它没有答案。 我也发现了很多其他类似的问题并尝试了这些答案,但都没有奏效。 我开始使用Android文档中的内容,并在通过其他问题时尝试了它的变体。 https://developer.android.com/guide/topics/ui/controls/button.html

如果在按钮上使用onTouch() ,则其onClick()功能将不起作用。 所以你可以通过为你触摸的按钮添加某些方法来让它工作,如下所示:

upButton.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            switch (motionEvent.getAction()){
                case MotionEvent.ACTION_DOWN:
                    textView.setText("Up button pressed.");
                    upButton.setPressed(true);
                    //Use this if you want to perform onClick() method.
                    //upButton.performClick();
                    break;
                case MotionEvent.ACTION_UP:
                    textView.setText("Up button released.");
                    upButton.setPressed(false);
                    break;
            }
            return true;
        }
    });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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