【问题标题】:Is there a way to specify android:layout_height dynamically during onCreate?有没有办法在 onCreate 期间动态指定 android:layout_height?
【发布时间】:2011-12-09 17:46:13
【问题描述】:

我想设置

android: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"
               />

【问题讨论】:

    标签: android android-layout textview


    【解决方案1】:

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

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

    在本例中,视图的高度为 50 像素。

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

    float dp = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 50,
                                         getResources().getDisplayMetrics()); 
    

    【讨论】:

    • 谢谢alextsc。但我的问题是即使这样做也没有反映。我的代码是这样的。 ViewGroup.LayoutParams lp = sometext.getLayoutParams(); lp.height = 10; sometext.setLayoutParams(lp);
    • 您是否使用findViewById() 来获取对本示例中使用的文本视图的引用?或者您是否从代码 (可能只是未添加到布局中) 创建一个新视图?还要测试你是否导入了正确的 LayoutParams,框架中有很多。右边是ViewGroup.LayoutParams这里。
    • 嗨,alextsc,它有效。看起来 apk 文件被缓存了。即使从 xml 中删除了几件事,它仍然可以正常工作:|所以删除了 .apk 并再次创建,我可以看到更改。谢谢
    • 没问题,很高兴能帮上忙。 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-29
    • 1970-01-01
    • 2023-01-19
    相关资源
    最近更新 更多