Фон вокруг круга Android становится овальным
Я хочу поместить круг в текстовое окно. Круг становится овальным при его рендеринге.
Мой макет XML:
<TextView
android:id="@+id/amount_key"
android:layout_weight="1"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:layout_marginRight="2dp"
android:gravity="center"
android:background="@drawable/circle"
android:layout_marginLeft="20dp"
android:text="3\ndays"
android:padding="20dp"
android:textColor="#ffffff"
android:textStyle="bold"
android:textSize="25dp" />
</LinearLayout>
Мой круг:
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<solid
android:color="#79bfea"/>
</shape>
Ответы
Ответ 1
- Измените свои
textView
layout_height
и layout_width
на wrap_content
- Добавьте тег размера внутри тега формы следующим образом
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">>
<solid android:color="#79bfea" />
<size android:height="25dp"
android:width="25dp"/>
</shape>
Если он все еще овальный, попробуйте увеличить ширину и высоту в теге размера. Это сработало для меня!
Ответ 2
Вы можете создать свой собственный Drawable, который будет ограничивать радиус до минимального значения между его шириной и высотой.
package com.example.android;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
public class ColorCircleDrawable extends Drawable {
private final Paint mPaint;
private int mRadius = 0;
public ColorCircleDrawable(final int color) {
this.mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
this.mPaint.setColor(color);
}
@Override
public void draw(final Canvas canvas) {
final Rect bounds = getBounds();
canvas.drawCircle(bounds.centerX(), bounds.centerY(), mRadius, mPaint);
}
@Override
protected void onBoundsChange(final Rect bounds) {
super.onBoundsChange(bounds);
mRadius = Math.min(bounds.width(), bounds.height()) / 2;
}
@Override
public void setAlpha(final int alpha) {
mPaint.setAlpha(alpha);
}
@Override
public void setColorFilter(final ColorFilter cf) {
mPaint.setColorFilter(cf);
}
@Override
public int getOpacity() {
return PixelFormat.TRANSLUCENT;
}
}
затем примените к вашему текстуру:
textView.setBackground(new ColorCircleDrawable(Color.RED));
Ответ 3
Я расширил класс TextView, чтобы установить ширину как высоту
public class TextViewSquareShaped extends TextView {
public TextViewSquareShaped(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(attrs);
}
public TextViewSquareShaped(Context context, AttributeSet attrs) {
super(context, attrs);
init(attrs);
}
public TextViewSquareShaped(Context context) {
super(context);
init(null);
}
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
}
private void init(AttributeSet attrs) {
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width = getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec);
setMeasuredDimension(width, width);
Log.v("measure", "width:" + width + " height:" + width);
}
}
И затем, в сочетании с ответом Судхасри, я могу показать точное круговое текстовое представление.
Поэтому нет необходимости указывать фиксированную высоту и вес.
Ответ 4
попробуйте кольцо вместо овального
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="ring" >
<solid android:color="#79bfea" />
</shape>
Ответ 5
Поскольку вы используете match_parent
для ширины и высоты и устанавливаете выделение в фоновом режиме, это будет овально. Для достижения круга вы можете задать одинаковые размеры для ширины и высоты. NA diff требуется полный экран, тогда вы можете использовать ширину от java
кода с помощью WindowManager
и установить одинаковое значение как по ширине, так и по высоте.
Ответ 6
Чтобы получить этот
![введите описание изображения здесь]()
Я использовал два LinearLayout внутри друг друга и установил родительскую гравитацию в CENTER
<LinearLayout
android:layout_width="80dp"
android:layout_height="50dp"
android:baselineAligned="false"
android:gravity="center"
android:orientation="vertical">
<LinearLayout
android:layout_width="45dp"
android:layout_height="45dp"
android:gravity="center"
android:background="@drawable/oval"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Text"
android:textSize="12sp" />
</LinearLayout>
</LinearLayout>
и это oval.xml внутри выделенной папки
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<solid android:color="#393939" />
<size
android:width="40dp"
android:height="40dp" />
</shape>
без внутреннего LinearLayout вы получите это
![введите описание изображения здесь]()
который он кодирует,
<LinearLayout
android:layout_width="80dp"
android:layout_height="50dp"
android:baselineAligned="false"
android:gravity="center"
android:background="@drawable/oval"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Text"
android:textSize="12sp" />
</LinearLayout>