[英]Android get Fragment width
我有一個包含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的片段。
謝謝。
您應該能夠將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檢查。 您可能還需要進行某種檢查,以確保只設置文本視圖的寬度一次,否則您可以進入無限的布局循環(不是世界末日,但對性能不利) 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.