[英]Android : setBackground method changes View's height
當我以編程方式更改背景顏色時,它會拉伸TextView
的寬度。
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
holder.textCategory.setText(categoryList.get(position).getName());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
if (categoryIndex == position) {
holder.textCategory.setBackground(context.getDrawable(R.drawable.categories_background));
} else {
holder.textCategory.setBackground(context.getDrawable(R.drawable.temp_background));
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
android:layout_margin="3dp"
android:background="@drawable/categories_background"
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:textStyle="bold"
android:fontFamily="sans-serif-light"
android:textAllCaps="true"
android:id="@+id/categoryName"
android:paddingBottom="10dp"
android:paddingTop="10dp"
android:paddingRight="10dp"
android:paddingLeft="10dp"
android:textColor="#262626"
android:textSize="16sp"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</androidx.cardview.widget.CardView>
每當我單擊時, TextView
的寬度都會變寬。 但是,我想保持寬度不變,只改變背景顏色。
里面有沒有空格或不同的字符? 你能通過調試來檢查它嗎? 謝謝
我也遇到了這個奇怪的問題,對我來說,更改背景顏色時控件的高度會失真,當發生失真時,我使用了以下解決方法:
if (backGroundColorChanged) {
ViewGroup.LayoutParams layoutParams = newBookmark.getLayoutParams();
Resources r = getResources();
float px = TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
25, // if I call setBackgroundColor, the height will be distorted -> set it to 25dp
r.getDisplayMetrics()
);
layoutParams.height = (int)px;
newBookmark.setBackgroundColor(myContext.getColor(R.color.green) );
newBookmark.setLayoutParams(layoutParams);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.