gut*_*ory 6 android fragment width textview
我有一个包含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>
Run Code Online (Sandbox Code Playgroud)
在第一个片段中,我有一个TableLayout,其中每行有一个自定义TextView.我想知道片段的宽度,因为如果自定义TextView比片段宽,我将设置所需的行数.
这是我在自定义TextView中所做的:
@Override
protected void onMeasure (int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
mMaxWidth = (float) (getMeasuredWidth());
}
Run Code Online (Sandbox Code Playgroud)
通过这一行,我得到了三个片段的宽度,而不仅仅是包含自定义TextView的片段.
谢谢.
Sam*_*udd 25
您应该能够将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;
}
}
});
Run Code Online (Sandbox Code Playgroud)
通过最初将TextView的宽度设置为0,可以防止它更改片段的宽度.然后,您可以使用视图树观察器在布局发生后获取您感兴趣的任何片段的宽度(通过查看其根视图).最后,您可以将TextView设置为精确的宽度,然后自动为您进行包装.
请注意,onGlobalLayout可以被多次调用,并且在所有视图完全布局之前定期调用,因此!= 0检查.您可能还需要进行某种检查,以确保只设置文本视图的宽度一次,否则您可以进入无限的布局循环(不是世界末日,但对性能不利) .
| 归档时间: |
|
| 查看次数: |
15992 次 |
| 最近记录: |