Android获取片段宽度
我有一个包含3个片段的布局:Android获取片段宽度,android,textview,width,fragment,Android,Textview,Width,Fragment,我有一个包含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 andr
<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>
通过这一行,我从三个片段中获得了宽度,而不仅仅是包含自定义TextView的片段
谢谢。您应该能够将TextView的宽度设置为fill\u parent,在这种情况下,它将为您进行包装。您不应该将布局的宽度设置为匹配父级,因为使用布局权重时效率低下 由于android的布局系统在视图大小方面有时很神秘,如果将TextView width设置为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!。它工作得很好。我花了这么多时间寻找我问题的答案。谢谢。知识渊博!。我添加了这个监听器,它给了我片段的宽度和高度,但它不会将我的内容拖到屏幕上,所以你能帮我解决这个问题吗
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;
}
}
});