更改文本大小后适合textview的内容

时间:2013-03-17 17:16:20

标签: android

我有文字观点:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:background="@drawable/item_table_light_grey"
          android:gravity="center"
          android:orientation="vertical" >

    <TextView
            android:id="@android:id/text1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#000000"
            />
</LinearLayout>

当我使用代码

更改文本大小时
TextView textView = (TextView) view.findViewById(android.R.id.text1);
textView.setTextSize(adapter.getTextSize());

尽管文本大小已成功更改,但textView的宽度和高度未更改。 我做错了什么?

2 个答案:

答案 0 :(得分:4)

Android一旦显示,就不会刷新带有“wrap_content”的视图布局。

因此,如果你添加一个子视图,或者动态修改内容,那就搞砸了。

为了解决这个问题,我编写了一个静态类,它重新计算大小并使用“wrap_content”强制更新视图的布局。使用的代码和说明可在此处获取:

https://github.com/ea167/android-layout-wrap-content-updater

另一个解决方案是将固定值设置为layout_width和layout_height,在TextView上添加gravity =“center”,并删除wrap_content

希望它有所帮助!

答案 1 :(得分:0)

对于任何人现在和将来都可能需要这样做,我做了一个技巧来解决。如果您的TextVew在LinearLayout中,例如。与orientation="vertical",然后将其放置:

android:layout_height="wrap_content"
android:layout_weight="1"
当文本更改时,

到TextView的高度将更新。 我不知道里面发生了什么,但这对我有用。