我想显示一行数字,每个数字打印在不同圆圈的中心。然而,集合的大小由用户输入确定。我所取得的成就是:
RelativeLayout myLayout = (RelativeLayout)findViewById(R.id.layout1);
// Creating a new TextView
TextView[] tv = new TextView[size+1];
TextView temptv;
for (i = 1; i <= size; i++) {
temptv = new TextView(MainActivity.this);
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
if (i > 1) {
lp.addRule(RelativeLayout.BELOW, R.id.textView5);
lp.addRule(RelativeLayout.RIGHT_OF, tv[i-1].getId());
}
else {
lp.addRule(RelativeLayout.BELOW, R.id.textView5);
lp.addRule(RelativeLayout.ALIGN_LEFT, R.id.textView5);
}
// width of Text
temptv.setWidth(60);
temptv.setHeight(60);
// size of Text
temptv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 25);
temptv.setGravity(Gravity.CENTER|Gravity.CENTER_VERTICAL);
temptv.setLayoutParams(lp);
myLayout.addView(temptv, lp);
answer = "<font color='#000000'>" + mynum[i] + "</font>";
// Update the label with our dynamic answer
temptv.setText(Html.fromHtml(answer));
temptv.setBackgroundResource(R.drawable.circle1);
tv[i] = temptv;
tv[i].setId(i);
}
它工作正常,但有一个问题。圆的半径始终是 TextView 宽度或高度的一半。所以在上面的例子中,半径始终是30,就像这张图:
如果 TextView 的宽度和高度不同(例如使用 temptv.setWidth(75);
和 temptv.setHeight(50);
),那么我得到椭圆形,就像这张图:pic2 http://i841.photobucket.com/albums/zz337/lilpengi/number2_zps767ec27f.png
无论circle1.xml中的形状设置如何:
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<corners android:radius="25dip"/>
<stroke android:color="#c00000" android:width="5dip"/>
<solid android:color="#ffffff"/>
</shape>
无论我将半径设置为10、25、50,结果都是一样的。我的代码出了什么问题?
最佳答案
对于标准的 Android 小部件,这似乎是不可能的,因为您在组件周围绘制了一个“椭圆形”。
椭圆形可以变成圆形,因为圆形是高度等于宽度的特殊化。我的建议是重新实现计算组件大小的方式。只需重写 onMeasure 即可使布局始终呈正方形(这是更简单的方法,请单击底部的链接):
class SquareTextView extends TextView{
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int size = 0;
int width = getMeasuredWidth();
int height = getMeasuredHeight();
if (width > height) {
size = height;
} else {
size = width;
}
setMeasuredDimension(size, size);
}
}
关于java - Android:TextView 中的圆半径始终由 TextView 宽度和高度固定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23634696/