有没有办法在onCreate期间动态指定android:layout_height?

时间:2011-12-09 17:46:13

标签: android android-layout textview

我想设置

  

机器人:layout_height = “的 WRAP_CONTENT

在应用程序启动期间

到某些像素( int )。这是一个textView,其背后的原因是我希望textView动态的高度基于我的结尾的一些输入,这些输入将在调用onCreate方法时计算。

这可能吗?如果是的话,任何一个例子都会很棒。

忘记添加我的textView xml看起来像这样

 <TextView
                android:id="@+id/sometext"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:fadingEdge="vertical"
                android:background="@drawable/dropshadow"
                android:scrollbars="vertical"
                android:text="Getting data on your slow n/w..."
                android:textColor="#ffffff"
               />

1 个答案:

答案 0 :(得分:6)

只需编辑视图的布局参数即可。

TextView v = (TextView) findViewById(R.id.sometext);
LayoutParams lp = v.getLayoutParams();
lp.height = 50;
v.setLayoutParams(lp);

在此示例中,视图将为50px高。

请注意,由于此处有许多设备规格,因此通常不建议对布局使用像素尺寸。而是使用dp (密度无关像素)。您可以通过以下方式从dp值计算像素尺寸(此处为50dp至px)

float dp = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 50,
                                     getResources().getDisplayMetrics()); 
相关问题