[英]Android: Radius of Circle in TextView Always Fixed by TextView Width and Height
我想顯示一行數字,每行都打印在不同圓圈的中心。 但是,集合的大小由用戶輸入決定。 我所取得的成就是:
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/相冊/ 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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.