突出显示按钮:Setcolor文件管理器无法正常工作

时间:2013-04-26 17:11:08

标签: android button highlight

我想在不使用任何图像的情况下按下和释放时突出显示一个按钮,所以我使用以下代码来自SO上的帖子,但它对我不起作用:

public class MainActivity extends Activity {

    ImageButton myButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    myButton = (ImageButton) findViewById(R.id.button);
    myButton.setOnTouchListener(new ButtonHighlighterOnTouchListener(myButton));
    }

    public class ButtonHighlighterOnTouchListener implements OnTouchListener {

    final ImageButton imageButton;

    public ButtonHighlighterOnTouchListener(final ImageButton imageButton) {
        super();
        this.imageButton = imageButton;
    }

    @Override
    public boolean onTouch(final View view, final MotionEvent motionEvent) {
        if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
        //grey color filter, you can change the color as you like
        imageButton.setColorFilter(Color.parseColor("#5F2444"));
        System.out.println("called down");
        } else if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
        imageButton.setColorFilter(Color.parseColor("#245F30"));
        System.out.println("called up");
        }
        return false;
    }

    }

这里有什么问题?

原帖在这里:How to make Button highlight?

2 个答案:

答案 0 :(得分:2)

好的,我已经自己解决了希望它也会帮助其他人

public static void buttonEffect(View button) {
    button.setOnTouchListener(new OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
        switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN: {
            v.getBackground().setColorFilter(0xe0f47521, PorterDuff.Mode.SRC_ATOP);
            v.invalidate();
            break;
        }
        case MotionEvent.ACTION_UP: {
            v.getBackground().clearColorFilter();
            v.invalidate();
            break;
        }
        }
        return false;
        }
    });
    }

您也可以更改颜色,快乐编码:)

答案 1 :(得分:0)

我建议你在开关中添加这个事件,否则当用户点击按钮并按住直到他关闭按钮时,按钮仍保持选中状态。

case MotionEvent.ACTION_CANCEL:
{
    v.getBackground().clearColorFilter();
    v.invalidate();
    break;
}

我希望我有所帮助