user1940676
user1940676

Reputation: 4448

Add a pressed state to any view same as the launcher icons

I would like to add a pressed state to most of my views, so that the view will be darken regardless of its background color/drawable without creating xml selector to each view.

Like in the launcher icons.

Like in the following picture the google analytics icon is darken when I press it:

enter image description here

Upvotes: 0

Views: 108

Answers (1)

Kevin Coppock
Kevin Coppock

Reputation: 134714

I'd recommend using a ColorFilter. Here's an example of one:

private ImageView mImageView;
private static final ColorFilter sDarkenFilter = new PorterDuffColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY);

public void onCreate (Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.grid_layout);

    mImageView = (ImageView) findViewById(R.id.image);
    mImageView.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch (View v, MotionEvent event) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    mImageView.setColorFilter(sDarkenFilter);
                    return true;
                case MotionEvent.ACTION_UP:
                    mImageView.clearColorFilter();
                    return true;
            }
            return false;
        }
    });
}

Upvotes: 1

Related Questions