【问题标题】:Listview items with rounded corners and adaptive colors具有圆角和自适应颜色的列表视图项目
【发布时间】:2013-03-27 01:35:16
【问题描述】:

我需要通过以下方式自定义列表视图的项目。每个项目都应该有一个圆角,并且项目的背景应该根据当前系统颜色自适应地改变(通过颜色过滤器(PorterDuff)或通过计算适当的 rgb 组件中的颜色偏移 - 这个东西已经编码,这不是主题这个问题,所以让我们假设我有一个特定的颜色可以在运行时用作背景)。

我可以通过在项目的布局文件中指定android:background 来轻松应用圆角,该布局文件指的是具有以下代码的形状:

<corners android:radius="5dp" />

问题是,不可能(据我所知)动态调整(从 Java 中)形状中的颜色。所以,我不能使用 XML 定义的形状方法,我转向使用 Java 编码的解决方案。

我的getView 方法中有类似的东西(对于背景是颜色而不是可绘制的情况):

PaintDrawable mDrawable = new PaintDrawable();
mDrawable.getPaint().setColor(Color.argb(calcColor, r, g, b));
int px = DP2PX(10);
mDrawable.setCornerRadius(px);
view.setBackgroundDrawable(mDrawable);

It does the thing, but when an item is selected or pressed my custom background overrides default selection background, which is a bug.所选项目必须以标准选择背景显示,但带有圆角。

我尝试对列表视图项使用子类LinearLayout 并在其中覆盖dispatchDrawonDraw,但奇怪的是这对角落没有影响。比如我找到了如下代码:

float radius = 10.0f;
Path clipPath = new Path();
RectF rect = new RectF(0, 0, this.getWidth(), this.getHeight());
clipPath.addRoundRect(rect, radius, radius, Path.Direction.CW);
canvas.clipPath(clipPath);
super.dispatchDraw(canvas);

与基于标准LinearLayout 的项目相比,这种自定义绘制的视图显示没有任何变化。

那么,问题是如何在列表视图项中结合圆角和自适应背景颜色?

【问题讨论】:

    标签: android android-listview


    【解决方案1】:

    我对我的问题有部分解决方案。 getView中的代码现在如下:

    PaintDrawable mDrawable = new PaintDrawable();
    mDrawable.getPaint().setColor(Color.argb(calcColor, r, g, b));
    int px = DP2PX(10);
    mDrawable.setCornerRadius(px);
    
    Drawable defaultBg = getResources().getDrawable(android.R.drawable.list_selector_background);
    
    StateListDrawable states = new StateListDrawable();
    states.addState(new int[] {android.R.attr.state_pressed}, defaultBg);
    states.addState(new int[] {android.R.attr.state_focused}, defaultBg);
    states.addState(new int[] { },  mDrawable);
    
    view.setBackgroundDrawable(states);
    

    这将为空闲视图应用圆角和自定义颜色,并为按下的视图显示默认选择背景,但后者显示时没有圆角。对于如何在默认选择器上应用圆角的任何建议,我将不胜感激。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-18
      • 2019-08-07
      • 1970-01-01
      相关资源
      最近更新 更多