Java Android:创建一个圆形的 TextView?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25203501/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 23:52:15  来源:igfitidea点击:

Android: Creating a Circular TextView?

javaandroidtextviewxml-layout

提问by codeme2020

My current simple XML is below, however i would like the 3 TextViews within it to be circular, rather than rectangular.

我当前的简单 XML 如下,但是我希望其中的 3 个 TextView 是圆形的,而不是矩形的。

How can I change my code to do so?

我怎样才能更改我的代码呢?

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/tvSummary1"
        android:layout_width="270dp"
        android:layout_height="60dp" >
    </TextView>

    <TextView
        android:id="@+id/tvSummary2"
        android:layout_width="270dp"
        android:layout_height="60dp" >
    </TextView>

    <TextView
        android:id="@+id/tvSummary3"
        android:layout_width="270dp"
        android:layout_height="60dp" >
    </TextView>

</LinearLayout>

Note: I want an actual circlenot the curved edge rectangle shown below:

注意:我想要一个实际的而不是下面显示的弯曲边缘矩形:

enter image description here

在此处输入图片说明

EDIT:

编辑:

current code:

当前代码:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/tvSummary1"
        android:layout_width="270dp"
        android:layout_height="60dp"
        android:text=" " 
        android:gravity="left|center_vertical"
        android:background="@drawable/circle"/>

    <TextView
        android:id="@+id/tvSummary2"
        android:layout_width="270dp"
        android:layout_height="60dp"
        android:background="@drawable/circle" >
    </TextView>

    <TextView
        android:id="@+id/tvSummary3"
        android:layout_width="270dp"
        android:layout_height="60dp"
        android:background="@drawable/circle" >
    </TextView>

</LinearLayout>

Current output:

电流输出:

enter image description here

在此处输入图片说明

回答by Tushar Gogna

Create an texview_design.xmlfile and populate it with the following code. Put it in res/drawable.

创建一个texview_design.xml文件并使用以下代码填充它。把它放在 res/drawable 中。

<shape xmlns:android="http://schemas.android.com/apk/res/android" >

        <solid android:color="#98AFC7" />

        <stroke
            android:width="2dp"
            android:color="#98AFC7" />

        <corners
            android:bottomLeftRadius="20dp"
            android:bottomRightRadius="20dp"
            android:topLeftRadius="20dp"
            android:topRightRadius="20dp" />

    </shape>

Then in your main XML file just add the following line for each TextView:

然后在您的主 XML 文件中为每个 TextView 添加以下行:

  android:background="@drawable/texview_design"


Second way (not recommended): circleDownload this circle and place it in your drawablefolder and then make it your TextView'sbackground. and then set the gravityto center.

第二种方式(不推荐): 圆圈下载这个圆圈并将其放在您的drawable文件夹中,然后将其设为您的TextView's背景。然后将 设置gravitycenter

Then it will look like this:

然后它看起来像这样:

enter image description here

在此处输入图片说明

回答by Remees M Syde

use this in your drawable

在你的 drawable 中使用它

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" 
    android:shape="oval">


    <solid android:color="#55ff55"/>


    <size android:height="60dp"
        android:width="60dp"/>

</shape>

Set background for the textview as this

将 textview 的背景设置为这样

回答by GrIsHu

Try out below drawable file. Create file named "circle" in your res/drawablefolder and copy below code:

试试下面的可绘制文件。在您的res/drawable文件夹中创建名为“circle”的文件并复制以下代码:

   <?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval" >

    <solid android:color="#FFFFFF" />

    <stroke
        android:width="1dp"
        android:color="#4a6176" />

    <padding
        android:left="10dp"
        android:right="10dp"
        android:top="10dp"
        android:bottom="10dp"
         />

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

</shape>

Apply it in your TextViewas below:

将其应用于您的TextView如下:

<TextView
        android:id="@+id/tvSummary1"
        android:layout_width="270dp"
        android:layout_height="60dp"
        android:text="Hello World" 
        android:gravity="left|center_vertical"
        android:background="@drawable/round_bg">

    </TextView>

enter image description here

在此处输入图片说明

回答by Phant?maxx

This my actually working solution

这是我实际工作的解决方案

<?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval"
    >
    <!-- The fill color -->
    <solid android:color="#ffff" />
    <!-- Just to add a border -->
    <stroke
        android:color="#8000"
        android:width="2dp"
    />
</shape>

Make sure your TextView width and height match (be the same in dp), if you want a perfect (unstretched) circle.

如果您想要一个完美的(未拉伸的)圆圈,请确保您的 TextView 宽度和高度匹配(在 dp 中相同)。

Make sure that the text fits into a circle, by either shortening your text OR enlarging your circle OR making your text size smaller OR reduce your padding/s, if any. OR a combination of the above suggestions.

通过缩短文本或扩大圆圈或缩小文本大小或减少填充(如果有),确保文本适合圆圈。或以上建议的组合。

[EDIT]

[编辑]

For what I can see in your pictures, you want to add too much text on a line, for pure circles.
Consider that the text should have a squareaspect, so you can either wrap it (use \n) or just put the numbers inside the circles and put the writings above or uder the corresponding circle.

对于我在你的图片中看到的,你想在一行上添加太多的文字,对于纯圆圈。
考虑到文本应该有一个方形的方面,因此您可以将它包裹起来(使用\n),或者只是将数字放在圆圈内,然后将文字放在相应的圆圈上方或下方。

回答by MysticMagic?

You can try this in round_tv.xmlin drawable folder:

您可以round_tv.xml在 drawable 文件夹中尝试此操作:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >

    <stroke android:color="#22ff55" android:width="3dip"/>

    <corners
        android:bottomLeftRadius="30dp"
        android:bottomRightRadius="30dp"
        android:topLeftRadius="30dp"
        android:topRightRadius="30dp" />

    <size
        android:height="60dp"
        android:width="60dp" />

</shape>

Apply that drawable in your textviews as:

在您的文本视图中应用该 drawable 为:

<TextView
    android:id="@+id/tv"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/round_tv"
    android:gravity="center_vertical|center_horizontal"
    android:text="ddd"
    android:textColor="#000"
    android:textSize="20sp" />

Output:

输出:

enter image description here

在此处输入图片说明

Hope this helps.

希望这可以帮助。

Edit: If your text is too long, Oval shape is more preferred.

编辑:如果你的文字太长,椭圆形更受欢迎。

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval">

    <stroke android:color="#55ff55" android:width="3dip"/>

    <corners
        android:bottomLeftRadius="30dp"
        android:bottomRightRadius="30dp"
        android:topLeftRadius="30dp"
        android:topRightRadius="30dp" />

    <size
        android:height="60dp"
        android:width="60dp" />

</shape>

Output:

输出:

enter image description here

在此处输入图片说明

If you still need it a proper circle, then I guess you will need to set its height dynamically after setting text in it, new height should be as much as its new width so as to make a proper circle.

如果你仍然需要一个合适的圆,那么我想你需要在其中设置文本后动态设置它的高度,新的高度应该和它的新宽度一样大,以便制作一个合适的圆。

回答by Mushtaq Jameel

Much of the Answer here seems to be hacks to the shape drawable, while android in itself supports this with the shapes functionality. This is something that worked perfectly for me.You can do this in two ways

这里的大部分答案似乎是对可绘制形状的黑客攻击,而 android 本身通过形状功能支持这一点。这对我来说非常有效。你可以通过两种方式做到这一点

Using a fixed height and width, that would stay the same regardless of the text that you put it as shown below

使用固定的高度和宽度,无论您放置什么文本,都将保持不变,如下所示

<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">

<solid android:color="@color/alpha_white" />

    <size android:width="25dp" android:height="25dp"/>

<stroke android:color="@color/color_primary" android:width="1dp"/>

</shape>

Using Paddingwhich re-adjusts the shape regardless of the text in the textviewit as shown below

使用 Padding重新调整形状而不考虑​​其中的文本,textview如下所示

<solid android:color="@color/alpha_white" />

<padding
    android:bottom="@dimen/semi_standard_margin"
    android:left="@dimen/semi_standard_margin"
    android:right="@dimen/semi_standard_margin"
    android:top="@dimen/semi_standard_margin" />

<stroke android:color="@color/color_primary" android:width="2dp"/>

semi_standard_margin = 4dp

semi_standard_margin = 4dp

回答by umerk44

The typical solution is to define the shape and use it as background but as the number of digits varies it's no more a perfect circle, it looks like a rectangle with round edges or Oval. So I have developed this solution, it's working great. Hope it will help someone.

典型的解决方案是定义形状并将其用作背景,但随着数字数量的变化,它不再是一个完美的圆形,它看起来像一个带有圆边或椭圆形的矩形。所以我开发了这个解决方案,它工作得很好。希望它会帮助某人。

Circular Text View

圆形文本视图

Here is the code of custom TextView

这是自定义TextView的代码

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.widget.TextView;

public class CircularTextView extends TextView
{
private float strokeWidth;
int strokeColor,solidColor;

public CircularTextView(Context context) {
    super(context);
}

public CircularTextView(Context context, AttributeSet attrs) {
    super(context, attrs);
}

public CircularTextView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
}


@Override
public void draw(Canvas canvas) {

    Paint circlePaint = new Paint();
    circlePaint.setColor(solidColor);
    circlePaint.setFlags(Paint.ANTI_ALIAS_FLAG);

    Paint strokePaint = new Paint();
    strokePaint.setColor(strokeColor);
    strokePaint.setFlags(Paint.ANTI_ALIAS_FLAG);

    int  h = this.getHeight();
    int  w = this.getWidth();

    int diameter = ((h > w) ? h : w);
    int radius = diameter/2;

    this.setHeight(diameter);
    this.setWidth(diameter);

    canvas.drawCircle(diameter / 2 , diameter / 2, radius, strokePaint);

    canvas.drawCircle(diameter / 2, diameter / 2, radius-strokeWidth, circlePaint);

    super.draw(canvas);
}

public void setStrokeWidth(int dp)
{
    float scale = getContext().getResources().getDisplayMetrics().density;
    strokeWidth = dp*scale;

}

public void setStrokeColor(String color)
{
    strokeColor = Color.parseColor(color);
}

public void setSolidColor(String color)
{
    solidColor = Color.parseColor(color);

}
}

Then in your XML, give some padding and make sure its gravity is center

然后在你的 XML 中,给一些填充并确保它的重力是中心

<com.app.tot.customtextview.CircularTextView
        android:id="@+id/circularTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="11"
        android:gravity="center"
        android:padding="3dp"/>

And you can set the stroke width

你可以设置笔画宽度

circularTextView.setStrokeWidth(1);
circularTextView.setStrokeColor("#ffffff");
circularTextView.setSolidColor("#000000");

回答by Javanator

It's a rectangle that prevents oval shape background to get circular.
Making view a square will fix everything.

它是一个矩形,可以防止椭圆形背景变成圆形。
使视图成为正方形将解决所有问题。

I found this solution to be clean and working for varying textsize and text length.

我发现这个解决方案很干净并且适用于不同的文本大小和文本长度。

public class EqualWidthHeightTextView extends TextView {

    public EqualWidthHeightTextView(Context context) {
        super(context);
    }

    public EqualWidthHeightTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public EqualWidthHeightTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        int r = Math.max(getMeasuredWidth(),getMeasuredHeight());
        setMeasuredDimension(r, r);

    }
}


Usage


用法

<com.commons.custom.ui.EqualWidthHeightTextView
    android:id="@+id/cluster_count"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:text="10+"
    android:background="@drawable/oval_light_blue_bg"
    android:textColor="@color/white" />


oval_light_blue_bg.xml


oval_light_blue_bg.xml

<shape xmlns:android="http://schemas.android.com/apk/res/android"<br>
       android:shape="oval">
   <solid android:color="@color/light_blue"/>
   <stroke android:color="@color/white" android:width="1dp" />
</shape>

回答by bheatcoker

I use: /drawable/circulo.xml

我使用:/drawable/circulo.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval">
    <solid android:angle="270"
        android:color="@color/your_color" />

</shape>

And then I use it in my TextView as:

然后我在我的 TextView 中使用它:

android:background="@drawable/circulo"

no need to complicated it.

没有必要把它复杂化。

回答by Vicky Vicent

I was also looking for a solution to this problem and as easy and comfortable I found, was to convert the shape of a rectangular TextView to cirular. With this method will be perfect:

我也在寻找解决这个问题的方法,我发现将一个矩形 TextView 的形状转换为圆形。有了这个方法就完美了:

  1. Create a new XML file in the drawable folder called "circle.xml" (for example) and fill it with the following code:

    <shape xmlns:android="http://schemas.android.com/apk/res/android"
        android:shape="oval">
    
        <solid android:color="#9FE554" />
    
        <size
            android:height="60dp"
            android:width="60dp" />
    
    </shape>
    
  1. 在名为“circle.xml”的 drawable 文件夹中创建一个新的 XML 文件(例如)并用以下代码填充它:

    <shape xmlns:android="http://schemas.android.com/apk/res/android"
        android:shape="oval">
    
        <solid android:color="#9FE554" />
    
        <size
            android:height="60dp"
            android:width="60dp" />
    
    </shape>
    

With this file you will create the new form of TextView. In this case, I created a circle of green. If you want to add a border, you would have to add the following code to the previous file:

使用此文件,您将创建 TextView 的新表单。在这种情况下,我创建了一个绿色圆圈。如果要添加边框,则必须将以下代码添加到前一个文件中:

    <stroke
        android:width="2dp"
        android:color="#FFFFFF" />
  1. Create another XML file ( "rounded_textview.xml") in the drawable folder with the following code:

    <?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:drawable="@drawable/circle" />
    </selector>
    
  1. 使用以下代码在 drawable 文件夹中创建另一个 XML 文件(“rounded_textview.xml”):

    <?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:drawable="@drawable/circle" />
    </selector>
    

This file will serve to change the way the TextView we eligamos.

这个文件将用于改变我们 eligamos 的 TextView 的方式。

  1. Finally, in the TextView properties we want to change the way section, we headed to the "background" and select the second XML file created ( "rounded_textview.xml").

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="H"
        android:textSize="30sp"
        android:background="@drawable/rounded_textview"
        android:textColor="@android:color/white"
        android:gravity="center"
        android:id="@+id/mark" />
    
  1. 最后,在我们想要更改方式部分的 TextView 属性中,我们前往“背景”并选择创建的第二个 XML 文件(“rounded_textview.xml”)。

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="H"
        android:textSize="30sp"
        android:background="@drawable/rounded_textview"
        android:textColor="@android:color/white"
        android:gravity="center"
        android:id="@+id/mark" />
    

With these steps, instead of having a TextView TextView rectagular have a circular. Just change the shape, not the functionality of the TextView. The result would be the following:

通过这些步骤,而不是让 TextView TextView 矩形有一个圆形。只需更改形状,而不是 TextView 的功能。结果如下:

enter image description here

在此处输入图片说明

Also I have to say that these steps can be applied to any other component having the option to "background" in the properties.

另外我不得不说,这些步骤可以应用于在属性中具有“背景”选项的任何其他组件。

Luck!!

运气!!