如果在使用setCompoundDrawables()
或setCompoundDrawablesWithIntrinsicBounds()
方法时无法显示图标,可能是以下几个原因导致的:
图标资源未正确设置或不存在:确保图标资源已正确设置,并且在指定路径下存在。可以通过getResources().getDrawable()
方法来获取图标资源。
图标尺寸过大导致无法显示:请确保图标的尺寸适合在TextView中显示。如果图标尺寸过大,可能会超出TextView的可见范围,导致无法显示。可以尝试调整图标的大小。
Drawable的位置未正确设置:setCompoundDrawables()
和setCompoundDrawablesWithIntrinsicBounds()
方法中,参数的位置顺序必须正确设置。一般来说,左边图标设置为第一个参数,上边图标设置为第二个参数,右边图标设置为第三个参数,下边图标设置为第四个参数。
以下是一个示例代码,演示如何使用setCompoundDrawables()
方法在TextView中显示一个左边的图标:
TextView textView = findViewById(R.id.text_view);
Drawable drawable = getResources().getDrawable(R.drawable.icon);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
textView.setCompoundDrawables(drawable, null, null, null);
在上面的示例中,首先获取了一个图标资源R.drawable.icon
,然后设置了图标的边界大小,最后通过setCompoundDrawables()
方法将图标设置到TextView的左边。
如果你想在其他位置显示图标,只需将setCompoundDrawables()
方法的参数位置调整为相应的位置即可。
希望以上解决方法能帮助到你!