您的位置:首页 > 移动开发 > Android开发

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

2017-12-22 16:55 190 查看
使用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);
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息