android imageview点击变暗,Android的imageview更改色调模拟按钮点击

happydude的答案是处理这个问题的最优雅的方式,但不幸的是(正如在评论中指出的那样)ImageView的源代码只接受一个整数(纯色)。 Issue 18220已经有几年解决这个,我已经发布了解决办法在那里我能在这里总结一下:

扩展的ImageView与代码包drawableStateChanged(),其基于新状态的色调:

TintableImageView.java

package com.example.widgets;

import android.content.Context;

import android.content.res.ColorStateList;

import android.content.res.TypedArray;

import android.util.AttributeSet;

import android.support.v7.widget.AppCompatImageView;

import com.example.R;

public class TintableImageView extends AppCompatImageView {

private ColorStateList tint;

public TintableImageView(Context context) {

super(context);

}

public TintableImageView(Context context, AttributeSet attrs) {

super(context, attrs);

init(context, attrs, 0);

}

public TintableImageView(Context context, AttributeSet attrs, int defStyle) {

super(context, attrs, defStyle);

init(context, attrs, defStyle);

}

private void init(Context context, AttributeSet attrs, int defStyle) {

TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.TintableImageView, defStyle, 0);

tint = a.getColorStateList(R.styleable.TintableImageView_tintColorStateList);

a.recycle();

}

@Override

protected void drawableStateChanged() {

super.drawableStateChanged();

if (tint != null && tint.isStateful())

updateTintColor();

}

private void updateTintColor() {

int color = tint.getColorForState(getDrawableState(), 0);

setColorFilter(color);

}

}

定义自定义属性:

attrs.xml

使用Widget和自定义属性与您当地的命名空间,而不是Android的:

example_layout。XML

xmlns:app="http://schemas.android.com/apk/res-auto"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:orientation="horizontal">

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:src="@drawable/example"

android:clickable="true"

app:tintColorStateList="@color/color_selector"/>

然后,您可以使用颜色选择像happydude建议:

color_selector.xml

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值