安卓-自动叠加触摸按下/高亮ImageButton状态

11
是否可以使用ImageButton在Android上实现触摸按下和高亮状态,而无需另外2个图像资源(考虑到h/m/ldpi,共6个)?我基本上想要与iOS类似的行为,即操作系统可以在按钮的触摸按下状态上放置半透明叠加层。我尝试在onTouch监听器中使用setColorFilter(0xFF000000, Mode.MULTIPLY),结果接近我想要的效果,但我不确定实现这一点的最佳状态处理方式:即1.触摸按下事件->更改颜色叠加层。 2.触摸抬起事件->删除颜色叠加层,并执行按钮动作。是否有更好的方法...或者有人能帮助填补空白部分?我不想使用单独的图像,原因有几个-它是一个iPhone端口,我还没有适当的资产,考虑到我必须考虑低/中/高创意。谢谢!
2个回答

1
如果您对 setColorFilter(0xFF000000, Mode.MULTIPLY) 感到满意,那么不妨自己制作一个扩展 ImageButton 的自定义组件呢?
类似于:
(很抱歉我还没有测试过这个)
package com.example;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ImageButton;

public class IosImageButton extends ImageButton implements OnTouchListener
{

    public IosImageButton(final Context context, final AttributeSet attrs, final int defStyle)
    {
        super(context, attrs, defStyle);
        this.init();
    }

    public IosImageButton(final Context context, final AttributeSet attrs)
    {
        super(context, attrs);
        this.init();
    }

    public IosImageButton(final Context context)
    {
        super(context);
        this.init();
    }

    private void init()
    {
        super.setOnTouchListener(this);
    }

    @Override
    public boolean onTouch(final View view, final MotionEvent event)
    {
        switch (event.getAction())
        {
            case MotionEvent.ACTION_DOWN:
                // touchDown event -> Change color overlay. goes here
                // e.g. this.setColorFilter(0xFF000000, Mode.MULTIPLY);
                return true;

            case MotionEvent.ACTION_UP:
                // touchUp event -> remove color overlay, and perform button action.
                // e.g. this.setColorFilter(0xFF000000, Mode.MULTIPLY);
                return true;

            default:
                return false;
        }
    }
}

然后是view.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <com.example.IosImageButton 
        <!-- add standard ImageButton setting here -->
        />

</RelativeLayout>

1
不要使用触摸事件来尝试显示类似东西的适当状态,否则你将不可避免地部分错误。框架会做很多工作来检测用户意图(例如:用户按下但然后滑动手指),考虑到诸如slop等因素。
对于ImageButton,您可以使用src属性来显示图标,然后使用适当的StateListDrawable作为背景。
我为您创建了一个快速项目,以便在Github上查看。
请注意,触摸状态显示在背景而非前景中。请参见{{link3:Google+上的讨论}},了解Android框架工程师为什么认为触摸反馈应该在后面而非前面。如果您仍希望drawable在前面,则请参见我的博客文章

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接