如何在代码中动态为TextView设置drawableRight

2025-05-22 11:29:02
推荐回答(1个)
回答(1):

1

    android:id="@+id/Title"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:layout_weight="1"
  android:drawableRight="@drawable/check_down"
  android:gravity="center_vertical"
  android:textSize="24dip"
  android:maxLines="1"
  android:ellipsize="end"/>
  我们写在xml的时候,都是这么写的。那代码呢?我们发现TextView他有一个方法
  2
  public void setCompoundDrawables (Drawable left, Drawable top, Drawable right, Drawable bottom);
  这个方法呢,就是可以在Java代码动态的画 左上右下几个方向
  类似于xml中的 android:drawableLeft="@drawable/icon"
  android:drawableTop="@drawable/icon"
  android:drawableRight="@drawable/icon"
  android:drawableButtom="@drawable/icon"
  3
  具体在代码中的用法是:
  Drawable drawable = getResources().getDrawable(R.drawable.spinner_checked);
  drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight()); //设置边界
  titleTv.setCompoundDrawables(null, null, drawable, null);//画在右边
  4
  运行之后的效果
  如何在代码中动态为TextView设置drawableRight
  如何在代码中动态为TextView设置drawableRight
  5
  界面比较丑,勿喷,大家也还可以通过这个方法实现
  public void setCompoundDrawablesWithIntrinsicBounds (Drawable left,
  Drawable top, Drawable right, Drawable bottom)