Android中DrawableLeft的使用

发布时间:2023-05-19

一、DrawableLeft是什么?

在Android中,Button、TextView等控件都支持设置Drawable,在按钮或文本的左边,上边,右边或下边显示Drawable。而“DrawableLeft”指的是在文本左边显示的Drawable,其它方向的Drawable分别是DrawableTop、DrawableRight、DrawableBottom。

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Button with drawable left"
    android:drawableLeft="@drawable/ic_launcher" />

二、为什么需要使用DrawableLeft?

使用DrawableLeft可以增强UI的美感,同时可以让界面更加清晰,突出信息的重要性。例如,在一个功能列表中,一个有用的图标能够告诉用户这个功能做了什么。 此外,使用DrawableLeft还可以优化用户交互,提高用户体验。例如,在搜索框中使用DrawableLeft的图标指示该搜索框的作用。

三、如何设置DrawableLeft?

1. 通过XML中设置DrawableLeft

可以通过xml的方式设置DrawableLeft

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Button with drawable left"
    android:drawableLeft="@drawable/ic_launcher" />

2. 动态设置DrawableLeft

也可以通过java代码的方式设置DrawableLeft,可以在运行时决定DrawableLeft的显示效果。

Button button = findViewById(R.id.button);
Drawable drawable = getResources().getDrawable(R.drawable.ic_launcher);
drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
button.setCompoundDrawables(drawable, null, null, null);

四、DrawableLeft的常见问题与解决方式

1. 图片大小不一致时如何处理?

当设置的图片大小不一致时,图片可能会因为缩放、拉伸等导致变形,需要手动调整图片的大小。方法如下:

Button button = findViewById(R.id.button);
Drawable drawable = getResources().getDrawable(R.drawable.ic_launcher);
DrawableCompat.setTint(drawable, getResources().getColor(R.color.colorPrimary));
drawable.setBounds(0, 0, DensityUtil.dp2px(20), DensityUtil.dp2px(20));
button.setCompoundDrawables(drawable, null, null, null);

2. 如何替换DrawableLeft中的图片?

替换DrawableLeft中的图片需要先获取原始DrawableLeft中的Drawable,然后通过setBounds方法修改Drawable的大小或不需要重新绘制,最后再通过setCompoundDrawables方法设置新的DrawableLeft。

Button button = findViewById(R.id.button);
Drawable drawable = button.getCompoundDrawables()[0];
Resources resources = getResources();
Drawable newDrawable = resources.getDrawable(R.drawable.new_drawable);
newDrawable.setBounds(0, 0, DensityUtil.dp2px(20), DensityUtil.dp2px(20));
button.setCompoundDrawables(newDrawable, null, null, null);

3. 如何设置DrawableLeft与文本间距?

如果需要设置DrawableLeft与文本间距,可以使用setCompoundDrawablePadding方法设置间距。

Button button = findViewById(R.id.button);
Drawable drawable = getResources().getDrawable(R.drawable.ic_launcher);
drawable.setBounds(0, 0, DrawableUtil.dp2px(20), DrawableUtil.dp2px(20));
button.setCompoundDrawables(drawable, null, null, null);
button.setCompoundDrawablePadding(DrawableUtil.dp2px(5));

4. 如何使DrawableLeft居中显示?

当设置的图片大小和文本大小不一致时,可能会导致DrawableLeft偏离文本的位置。这时候可以通过setGravity和setPadding方法来将DrawableLeft居中显示。

Button button = findViewById(R.id.button);
Drawable drawable = getResources().getDrawable(R.drawable.ic_launcher);
drawable.setBounds(0, 0, DrawableUtil.dp2px(20), DrawableUtil.dp2px(20));
button.setCompoundDrawables(drawable, null, null, null);
button.setGravity(Gravity.CENTER_VERTICAL | Gravity.START);
button.setPadding(DrawableUtil.dp2px(10), 0, 0, 0);