cod*_*e22 261 android textview android-drawable
我在这里有一个xml的textView.
<TextView
android:id="@+id/bookTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:drawableLeft="@drawable/checkmark"
android:gravity="center_vertical"
android:textStyle="bold"
android:textSize="24dip"
android:maxLines="1"
android:ellipsize="end"/>
Run Code Online (Sandbox Code Playgroud)
如您所见,我将DrawableLeft设置为xml.
我想在代码中更改drawable.
无论如何要去做这件事吗?或者在文本视图的代码中设置drawableLeft?
Bra*_*ash 729
你可以使用setCompoundDrawablesWithIntrinsicBounds(int left,int top,int right,int bottom)
设置0,你不想要图像
左侧Drawable示例:
TextView textView = (TextView) findViewById(R.id.myTxtView);
textView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.icon, 0, 0, 0);
Run Code Online (Sandbox Code Playgroud)
提示:每当您知道任何XML属性但没有关于如何在运行时使用它的线索时.只需转到开发人员doc中对该属性的描述即可.如果在运行时支持相关方法,您将在其中找到它.即对于DrawableLeft
Gib*_*olt 10
您可以创建扩展功能或直接使用setCompoundDrawablesWithIntrinsicBounds。
fun TextView.leftDrawable(@DrawableRes id: Int = 0) {
this.setCompoundDrawablesWithIntrinsicBounds(id, 0, 0, 0)
}
Run Code Online (Sandbox Code Playgroud)
如果需要调整drawable的大小,可以使用这个扩展功能。
textView.leftDrawable(R.drawable.my_icon, R.dimen.icon_size)
fun TextView.leftDrawable(@DrawableRes id: Int = 0, @DimenRes sizeRes: Int) {
val drawable = ContextCompat.getDrawable(context, id)
val size = resources.getDimensionPixelSize(sizeRes)
drawable?.setBounds(0, 0, size, size)
this.setCompoundDrawables(drawable, null, null, null)
}
Run Code Online (Sandbox Code Playgroud)
要真正花哨,请创建一个允许修改大小和/或颜色的包装器。
textView.leftDrawable(R.drawable.my_icon, colorRes = R.color.white)
fun TextView.leftDrawable(@DrawableRes id: Int = 0, @DimenRes sizeRes: Int = 0, @ColorInt color: Int = 0, @ColorRes colorRes: Int = 0) {
val drawable = drawable(id)
if (sizeRes != 0) {
val size = resources.getDimensionPixelSize(sizeRes)
drawable?.setBounds(0, 0, size, size)
}
if (color != 0) {
drawable?.setColorFilter(color, PorterDuff.Mode.SRC_ATOP)
} else if (colorRes != 0) {
val colorInt = ContextCompat.getColor(context, colorRes)
drawable?.setColorFilter(colorInt, PorterDuff.Mode.SRC_ATOP)
}
this.setCompoundDrawables(drawable, null, null, null)
}
Run Code Online (Sandbox Code Playgroud)
您可以使用以下任何方法在TextView上设置Drawable:
1- setCompoundDrawablesWithIntrinsicBounds(int,int,int,int)
2- setCompoundDrawables(Left_Drawable,Top_Drawable,Right_Drawable,Bottom_Drawable)
并且可以从您可以使用的资源中获取:
getResources().getDrawable(R.drawable.your_drawable_id);
Run Code Online (Sandbox Code Playgroud)
Kotlin 扩展 + 可绘制周围的一些填充
fun TextView.addLeftDrawable(drawable: Int, padding: Int = 32) {
val imgDrawable = ContextCompat.getDrawable(context, drawable)
compoundDrawablePadding = padding
setCompoundDrawablesWithIntrinsicBounds(imgDrawable, null, null, null)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
157401 次 |
| 最近记录: |