【问题标题】:Android get Fragment widthAndroid获取片段宽度
【发布时间】:2012-04-08 08:48:33
【问题描述】:

我有一个包含 3 个片段的布局:

<LinearLayout android:id="@+id/acciones"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">

<LinearLayout
android:id="@+id/fragment1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1">

</LinearLayout>


<LinearLayout
android:id="@+id/fragment2"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1">

</LinearLayout>

<LinearLayout
android:orientation="vertical"
android:id="@+id/f3"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1">

</LinearLayout>

</LinearLayout>

在第一个片段中,我有一个 TableLayout,其中每一行都有一个自定义 TextView。 我想知道片段的宽度,因为如果自定义的 TextView 比片段宽,我会设置必要的行数。

这是我在自定义 TextView 中所做的:

@Override
protected void onMeasure (int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);

mMaxWidth = (float) (getMeasuredWidth());
}

通过这一行,我得到了三个片段的宽度,而不仅仅是包含自定义 TextView 的片段。

谢谢。

【问题讨论】:

    标签: android textview width fragment


    【解决方案1】:

    您应该能够将 TextView 的宽度设置为 fill_parent,在这种情况下,它将为您进行包装。您不应该将布局的宽度设置为 match_parent,因为当您使用布局权重时它效率低下。

    由于 android 的布局系统在视图大小方面有时很神秘,如果将 TextView 宽度设置为 fill_parent 实际上会使其占据整个屏幕(正如您的问题所暗示的那样),请执行以下操作:

    默认情况下将您的 TextView 宽度设置为 0。在您的活动的 onCreate 中,设置内容视图后:

    findViewById(R.id.acciones).getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            final int fragmentWidth = findViewById(R.id.releventFragmentId).getWidth();
            if (fragmentWidth != 0){
                findViewById(R.id.yourTextViewId).getLayoutParams().width = fragmentWidth;
            }
        }
    });
    

    通过最初将 TextView 的宽度设置为 0,可以防止它更改片段的宽度。然后,您可以使用视图树观察器在布局发生后获取您感兴趣的任何片段的宽度(通过查看其根视图)。最后,您可以将您的 TextView 设置为精确的宽度,然后它会自动为您进行包装。

    请注意,onGlobalLayout 可以多次调用,并且会在所有视图完全布局之前定期调用,因此需要检查 != 0。您可能还需要进行某种检查以确保您只设置一次文本视图的宽度,否则您可能会进入无限布局循环(不是世界末日,但对性能不利) .

    【讨论】:

    • 神奇的触感 Monkeyless!。它工作得很好。我花了很多时间来寻找我的问题的解决方案。非常感谢。知识渊博!。
    • 我已经添加了这个监听器,它给了我片段的宽度和高度,但它不会将我的内容绘制到屏幕上,所以你能帮忙解决这个问题
    猜你喜欢
    • 2013-06-01
    • 2017-10-01
    • 1970-01-01
    • 2013-07-19
    • 1970-01-01
    • 1970-01-01
    • 2011-11-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多