使用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);
}
}
}
}