【问题标题】:TextView with rounded background带有圆形背景的 TextView
【发布时间】:2018-01-20 17:45:05
【问题描述】:

我正在为每条消息制作一个具有这种形状的背景的信使应用程序:

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<corners
    android:bottomLeftRadius="80dp"
    android:bottomRightRadius="80dp"
    android:topRightRadius="80dp"
    android:topLeftRadius="80dp"
   />
<solid android:color="#fff"/>

但问题是当消息很长时角落很大,这使我的消息布局很糟糕!我想知道是否有另一种方法可以制作圆形背景!

【问题讨论】:

标签: java android


【解决方案1】:

您可以使用 9-patch 可绘制对象。

这些是 png 文件,允许您定义无法拉伸的区域以及无论视图大小都将保持相同大小的区域。

你可以在这里阅读: https://developer.android.com/guide/topics/graphics/2d-graphics.html#nine-patch

您可以在此处阅读有关如何创建它的信息: https://developer.android.com/studio/write/draw9patch.html

9-patch drawables 常用于 Adnroid SDK 标准视图。

【讨论】:

    【解决方案2】:

    您可以创建一个扩展 Button 类的自定义按钮类,然后覆盖 onLayout() 方法可能是这样的......基本上您正在设置 corner radius = height/2

        @Override
        protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
            super.onLayout(changed, left, top, right, bottom);
            if(this.getBackground()!=null && this.getBackground() instanceof LayerDrawable) {
                LayerDrawable layerDrawable = (LayerDrawable)(this.getBackground().mutate());
                GradientDrawable gd1 = (GradientDrawable)layerDrawable.findDrawableByLayerId(R.id.layer_one);
                roundEdgeGradientDrawable(gd1, this.getHeight());
            }
        }
    
        public static GradientDrawable roundEdgeGradientDrawable(GradientDrawable bgShape, float height) {
            if (bgShape != null) {
                float radius = height / 2;
                float[] radii = {radius, radius, radius, radius, radius, radius, radius, radius};
                bgShape.setCornerRadii(radii);
            }
            return bgShape;
        }
    

    【讨论】:

      【解决方案3】:
      <?xml version="1.0" encoding="utf-8"?>
            <shape xmlns:android="http://schemas.android.com/apk/res/android" >
            <solid android:color="@color/headerColor" />      
            <corners android:radius="5dp" />
      </shape>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-10-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-03-18
        • 2020-03-21
        相关资源
        最近更新 更多