现在的位置: 首页 > 综合 > 正文

setBackgroundResource 9 patch图会影响 LinearLayout的Padding

2019年10月09日 ⁄ 综合 ⁄ 共 1886字 ⁄ 字号 评论关闭
 <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content">
            <TextView
                android:id="@+id/order_tag_1"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:background="@drawable/order_tag_select"
                android:gravity="center"
                android:paddingBottom="10dip"
                android:paddingTop="10dip"
                android:text="TAG1"
                android:textColor="#e33531"
                android:textSize="18dip"/>
            <TextView
                android:id="@+id/order_tag_2"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:background="@drawable/order_tag"
                android:gravity="center"
                android:paddingBottom="10dip"
                android:paddingTop="10dip"
                android:text="TAG2"
                android:textSize="18dip"/>
        </LinearLayout>

布局大概是这样子的。当切换tag的时候

public void setTagStyle(int position) {
		int unSelectId = position == 0 ? 1 : 0;
		mTag[position].setTextColor(Color.parseColor("#e33531"));
		mTag[position].setBackgroundResource(R.drawable.order_tag_select);
		mTag[unSelectId].setTextColor(Color.parseColor("#666666"));
		mTag[unSelectId].setBackgroundResource(R.drawable.order_tag);
	}

对tag的背景图片进行设置

setBackgroundResource

设置完以后会发现layout中设置的TextVIew的padding属性不见了

http://stackoverflow.com/questions/10095196/whered-padding-go-when-setting-background-drawable

http://stackoverflow.com/questions/2886140/does-changing-the-background-also-change-the-padding-of-a-linearlayout

This is the default behavior when changing the background Drawable on
View.
According to Romain Guy, one of the Android developers, "The reason why setting an image resets the padding is because 9-patch images can encode padding." See his full answer in a similar
question
.

The fix is to reset the padding in code each time you change the background drawable.

What I found was adding a 9 patch as a background resource reset the padding - although interestingly if I added a color, or non-9
patch image, it didn't. The solution was to save the padding values before the background gets added, then set them again afterwards.

当设置9 patch图的时候会重置padding。其他的不会

抱歉!评论已关闭.