Android获取Fragment宽度

标签 android textview width fragment

我有一个包含 3 个 fragment 的布局:

<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>

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

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

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

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

通过这一行,我从三个 Fragment 中获取了宽度,而不仅仅是包含自定义 TextView 的 Fragment。

谢谢。

最佳答案

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

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

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

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,可以防止它更改 fragment 的宽度。然后,您可以使用 View 树观察器在布局发生后获取您感兴趣的任何 fragment 的宽度(通过查看其 Root View )。最后,您可以将 TextView 设置为该宽度,它会自动为您换行。

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

关于Android获取Fragment宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9845197/

相关文章:

android - Firemonkey TWebBrowser 输入替代?

wpf - 给 WPF Grid 一个 ScrollViewer 减去滚动条的宽度

html - 如何在不导致换行符的情况下将元素的宽度指定为最大?

java - Libgdx 和 Dagger 2 - 不生成代码

java - 某个范围内的随机数生成器有时会输出相同的数字两次

java - SwipeRefreshLayout 不遵守约束

android - 在 TextView 中为特定字符设置下标和上标?

Android - 省略并截断 TextView 中的所有长网址

android - 用另一个类更改一个类的 TextView

css - 如何并排跨越两个 div 以获得全屏宽度?