android:layout_weight属性についてあなたが知らないこと

私が最初にAndroid開発を始めたとき、xmlでレイアウトを書くときにandroid:layout_weight属性を使用しました。
まず、属性はリニアレイアウトレイアウトで有効である必要があります。
この属性は重みの意味です。ビューの幅または高さは、元の幅または高さ(android:layout_width)に残りのスペースの比率を加えたものに等しくなります。(ここの残りのスペースに注意してください)

コードに直接:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    tools:context="com.dgg1.weight.MainActivity">

    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:background="#ff00ff"
        android:text="按钮1" />

    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="2"
        android:background="#ffff00"
        android:text="按钮2" />
</LinearLayout>

達成された効果:
ここに写真の説明を書いてください

これは公式の書き方でもあります。

書き方を変えさせてください。

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    tools:context="com.dgg1.weight.MainActivity">

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:background="#ff00ff"
        android:text="按钮1" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="2"
        android:background="#ffff00"
        android:text="按钮2" />
</LinearLayout>

ねえ、これはまったく同じではありません(ねえ、注意深く見ない人は本当にそれが変更されていないと思うかもしれません)ここで私はlayout_widthを0からmatch_parentに変更しました。
達成された効果:
ここに写真の説明を書いてください

効果が前の効果と正反対であることがわかりますが、なぜこの効果が発生するのですか?layout_weight属性の意味は、コントロールの元の幅+残りのスペースの比例幅です。
最初のケース:画面の幅を100とすると、幅を0dpに設定すると、button2の幅は0(コントロールの幅)+ 100(残りの幅)* 2/3(比率)= 67 (実際の幅)、button1の幅は0 + 100 * 1/3 = 33です。

ケース2:画面の幅を100とすると、幅をmatch_parentに設定すると、button1の幅が100になり、button2の幅も100になり、残りの幅は100-(100 + 100)=-になります。 100(残りの幅は-100)、次にbutton1の実際の幅を100 +(-100)* 1/3 = 67に変換し、button2の実際の幅を100 +(-100)* 2/3 = 33に変換し続けます。 。
したがって、まったく逆の結果になります。(公式の推奨事項は、最初の書き込み方法を使用することです)

ただし、includeタグの再利用レイアウトを使用する場合は、2番目の書き込み方法が必要になることがあります。

(質問や脱落がある場合は、メッセージを残して話し合い、一緒に進歩してください)

おすすめ

転載: blog.csdn.net/qq77485042/article/details/77446571