【发布时间】:2018-12-23 02:55:30
【问题描述】:
我必须向 TextView 添加背景形状,但我不知道这个的尺寸,因为我需要设置宽度以匹配父级。我无法设置尺寸 dp,因为它会导致我在调整大小、键盘显示和其他方面出现更多问题。 我会在创建时获得有效的宽度,并在高度上设置相同的宽度,但是当我写的时候:
TextView tCircle = findViewById(R.id.tCircle);
tCircle.getLayoutParams().width
它给我-1。 这个圆圈怎么画?? button_shape 是:
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval">
<corners android:radius="10dp"/>
<stroke android:color="@color/colorPrimaryDark"
android:width="2dp"/>
<solid android:color="@color/colorAccent"/>
</shape>
布局片段
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="6.5"
android:baselineAligned="false"
android:orientation="horizontal">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="vertical">
<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName"
android:text="Name" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="horizontal">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center"
android:orientation="horizontal">
<TextView
android:id="@+id/tCircle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:autoSizeTextType="uniform"
android:background="@drawable/button_shape"
android:text="TextView"
android:textAlignment="center" />
</LinearLayout>
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
编辑: 根据 Mohamed Mohaideen AH 的建议,我在 onCreate 中写道:
tCircle.post(new Runnable() {
@Override
public void run() {
int width = tCircle.getWidth();
int heigth = tCircle.getHeight();
Log.d(TAG_LOG, "Dim cerchio: W" + String.valueOf(width)+" H:"+String.valueOf(heigth));
if(width>=heigth){
Log.d(TAG_LOG, "A");
tCircle.setWidth(heigth);
tCircle.setHeight(heigth);
}
else{
Log.d(TAG_LOG, "B");
tCircle.setWidth(width);
tCircle.setHeight(width);
}
}
});
TextView 是:
<TextView
android:id="@+id/tCircle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:autoSizeTextType="uniform"
android:background="@drawable/button_shape"
android:text="TextView"
android:textAlignment="center" />
但是集合不会改变维度。为什么?
【问题讨论】:
标签: android android-layout textview android-shape