繁体   English   中英

Android:setBackground 方法更改视图的高度

[英]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的宽度都会变宽。 但是,我想保持宽度不变,只改变背景颜色。

这是 GENERAL 选项卡的未选择语句这是 GENERAL 选项卡的未选择语句

这是选定的语句这是选定的语句

里面有没有空格或不同的字符? 你能通过调试来检查它吗? 谢谢

我也遇到了这个奇怪的问题,对我来说,更改背景颜色时控件的高度会失真,当发生失真时,我使用了以下解决方法:

        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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM