Android XML布局weightSum配置异常:文本与图片显示错位求助
Fixing Your LinearLayout Weight Layout Issue
Hey there! Let's sort out why your inner text view is misaligned. The problem lies in incorrect layout_width values paired with layout_weight—a common gotcha in Android LinearLayouts.
Key Issues in Your Original Code
- The inner
LinearLayout(holding the text and image) useslayout_width="wrap_content"instead of0dp. Since it's supposed to take up 2 of the outer layout's 4 weight units,layout_widthmust be0dpforlayout_weightto properly claim the space. - The inner
TextViewandImageViewalso uselayout_width="wrap_content"withlayout_weight. This breaks the weight calculation, causing the text to shift left instead of taking its intended share of the space.
Corrected XML Code
<LinearLayout android:id="@+id/outcomess" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:weightSum="4" android:layout_marginTop="4dp" android:paddingBottom="10dp" android:layout_below="@+id/statuss"> <TextView android:id="@+id/text_outcome" style="@style/Base.TextAppearance.AppCompat.Subhead" android:layout_width="0dp" android:layout_height="wrap_content" android:paddingLeft="16dp" android:paddingRight="16dp" android:text="Outcome" android:textStyle="bold" android:layout_weight="2" android:textColor="@color/gray" android:textSize="15sp" /> <LinearLayout android:layout_width="0dp" <!-- Changed from wrap_content to 0dp --> android:layout_height="wrap_content" android:orientation="horizontal" android:weightSum="2" android:layout_weight="2"> <!-- Added this to take 2 units from outer weightSum --> <TextView android:id="@+id/outcome" style="@style/Base.TextAppearance.AppCompat.Subhead" android:layout_width="0dp" <!-- Changed from wrap_content to 0dp --> android:layout_height="wrap_content" android:text="Not Interested" android:layout_weight="1" android:textColor="@color/gray" android:textSize="15sp"/> <ImageView android:id="@+id/image" android:layout_width="0dp" <!-- Changed from wrap_content to 0dp --> android:layout_height="20dp" android:layout_weight="1" android:src="@drawable/ic_thumb_up_black_24dp"/> </LinearLayout> </LinearLayout>
What Changed & Why
- Inner LinearLayout: Set
layout_width="0dp"and addedlayout_weight="2"—this ensures it takes exactly half the outer layout's space (2 out of 4 weight units). - Inner TextView & ImageView: Set their
layout_width="0dp"solayout_weight="1"works as intended, splitting the inner LinearLayout's space evenly between them. Now the text will stay properly aligned in its allocated space instead of shifting left.
内容的提问来源于stack exchange,提问作者jyothi dadi
相关产品推荐
相关产品推荐

