【发布时间】:2012-08-11 09:41:19
【问题描述】:
我从各种不同的角度来解决这个问题。基本上要点是这样的:
我已经为需要以编程方式运行的接口设计了一个 XML 模板,因此它将在运行期间动态填充。
这里的问题是 XML TextView 有很多布局调整(有效)并且是必要的。但如果我真的在代码中设置它们,TextView 甚至不会出现。
(顺便说一下,TextView 嵌套在 TableRow 中,因此调用了 weight。) 我首先设计的用作代码参考的 XML 模板是这样的,它工作得很好:
<TextView
android:id="@+id/txtviewWhiteBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1.0"
android:background="@drawable/textview_9patch_white"
android:gravity="center"
android:text="75"
android:textColor="@android:color/black"
android:layout_margin="20dp"
android:padding="20dp"
android:textSize="40dp" />
就像我说的那样,布局完美。 但是,当我在代码中运行相同的布局并应用 LayoutParams 时,TextView 消失了。
这是相关的sn-p:
int textViewExampleID = 9001;
private TextView txtviewExample = new TextView(this);
private void buildTextView(){
LayoutParams paramsExample = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT,1.0f);
txtviewExample.setId(textViewExampleID);
txtviewExample.setBackgroundResource(R.drawable.textview_9patch_white);
txtviewExample.setGravity(Gravity.CENTER);
txtviewExample.setTextColor(getResources().getColor(android.R.color.black));
paramsExample.setMargins(20, 20, 20, 20);
txtviewExample.setPadding(20, 20, 20, 20);
txtviewExample.setTextSize(40);
txtviewExample.setText("customExample");
//if I comment out the following line, this TextView displays.
//if I leave it in, it doesn't display.
txtviewExample.setLayoutParams(paramsExample);
}
我意识到 LayoutParams 有各种可用的类,我一直在使用它们 LinearLayout.LayoutParams、TableView.LayoutParams、RelativeLayout.LayoutParams、LayoutParams 本身... 无论我尝试哪一个,任何调用“setLayoutParams”的尝试都会使整个 TextView 消失。 我已经搜索了这里的论坛,但还没有找到答案。这不会那么罕见。
【问题讨论】:
-
你试过
TableRow.LayoutParamsdeveloper.android.com/reference/android/widget/… -
我刚刚做了,(昨晚错过了这条评论,darnit),它成功了。谢谢大佬
标签: android textview layoutparams