ViewGroup点击时修改内部View状态或透明度

使用ViewGroup包裹View作为RecyclerView等列表控件中item的布局是一种常见的场景,点击item的时候如果希望修改子View的透明度则可以给重写ViewGroup,修改setPressed(boolean pressed)方法,在pressed参数为true时,给所有的子View设置透明度或者设置其他按压时需要显示的状态,在pressed参数为false时恢复为之前的状态即可,下面是一个自定义FrameLayout,实现了按压状态时内部所有View透明度的修改,但要记得给FrameLayout设置点击事件OnClickListener,否则看不到效果

/**
 * 给子view设置点击后透明度变化
 */

public class PressAlphaFrameLayout extends FrameLayout {

    public PressAlphaFrameLayout(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public PressAlphaFrameLayout(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public void setPressed(boolean pressed) {
        super.setPressed(pressed);
        if (pressed) {
            for (int i = 0; i < getChildCount(); i++) {
                View view = getChildAt(i);
                view.setAlpha(0.6f);
            }
        } else {
            for (int i = 0; i < getChildCount(); i++) {
                View view = getChildAt(i);
                view.setAlpha(1.0f);
            }
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值