Androidのレイアウトの重みの本当の意味



True Meaning Android Layout Weight



最初に、このプロパティがLinearlayoutでのみ有効であることを宣言します。 android:layout_weightが物議を醸している理由は、android:layout_widthをwrap_contentとmatch_parentに設定すると、2つの反対の効果が発生するためです。次のように:



<LinearLayout android:layout_width='match_parent' android:layout_height='wrap_content' android:orientation='horizontal' > <TextView android:layout_width='match_parent' android:layout_height='wrap_content' android:layout_weight='1' android:background='@android:color/black' android:text='111' android:textSize='20sp' /> <TextView android:layout_width='match_parent' android:layout_height='wrap_content' android:layout_weight='2' android:background='@android:color/holo_green_light' android:text='222' android:textSize='20sp' />
上記のレイアウトでは、両方のTextViewの幅がmatch_parentに設定されており、重みは1、重みは2です。効果は次のとおりです。


重量が3分の2ではなく1であることがわかります。



次のレイアウトを見てください。

<LinearLayout android:layout_width='match_parent' android:layout_height='wrap_content' android:orientation='horizontal' > <TextView android:layout_width='wrap_content' android:layout_height='wrap_content' android:layout_weight='1' android:background='@android:color/black' android:text='111' android:textSize='20sp' /> <TextView android:layout_width='wrap_content' android:layout_height='wrap_content' android:layout_weight='2' android:background='@android:color/holo_green_light' android:text='222' android:textSize='20sp' /> LinearLayout>
つまり、幅はwrap_contentであり、ビューは次のとおりです。




左側のTextViewは3分の1で通常です。

android:layout_weightの本当の意味は次のとおりです。Viewがプロパティを設定すると(有効であると仮定)、Viewの幅は元の幅(android:layout_width)に残りのスペースの比率を加えたものに等しくなります。

画面の幅をLとします。両方のビューの幅がmatch_parentで、元の幅がLで、両方のビューの幅がLの場合、残りの幅はL-(L + L)=-Lです。左側のビューは全体の3分の1を占めるため、全体の幅はL +(-L)* 1/3 =(2/3)Lになります。実際、デフォルトのビューの重みは0です。この値が設定されると、ビューが描画されるときにビューが2回実行される理由はここにあります。

Googleは、weight属性を使用する場合、幅を0dipに設定すると、効果はwrap_contentの設定と同じになることを公式に推奨しています。この重量はパーセンテージで理解できます!


次に、私の先生である神の人工知能チュートリアルを共有します。ゼロベース!わかりやすい!ユーモラス!黄色の段落も!私たちの人工知能チームにもぜひご参加ください。 https://blog.csdn.net/jiangjunshow