Android On Focus Listener and On Click Listener on ImageView

a 夏天 提交于 2019-12-06 12:32:53

It's the way the widget framework is designed.

When you look at View.onTouchEvent() code, you'll find out that the click action is performed only if the view has taken focus:

    // take focus if we don't have it already and we should in
    // touch mode.
    boolean focusTaken = false;
    if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
        focusTaken = requestFocus();
    }

    if (!mHasPerformedLongPress) {
        // This is a tap, so remove the longpress check
        removeLongPressCallback();

        // Only perform take click actions if we were in the pressed state
        if (!focusTaken) {
            // click
        }
    }

So, as you noticed, the first click makes the view gain focus. The second one will trigger the click handler since the view already has focus.

If you want to alter the bitmap of the ImageView when it's pressed, you should implement an View.OnTouchListener and set it via ImageView.setOnTouchListener() method. That listener should look more or less like this:

private View.OnTouchListener imageTouchListener = new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            // pointer goes down
            ivMenu01.setImageBitmap(Utility.getBitmap("Home_ford_focus.png"));
        } else if (event.getAction() == MotionEvent.ACTION_UP) {
            // pointer goes up
            ivMenu01.setImageBitmap(Utility.getBitmap("Home_ford.png"));
        }
        // also let the framework process the event
        return false;
    }
};

You can also use a Selector aka State List Drawable to achieve the same thing. See reference here: http://developer.android.com/guide/topics/resources/drawable-resource.html#StateList

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!