有没有一种方法可以在动态创建的每个文本视图中放置drawable


val textView = TextView(this)
val params = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT)
params.setMargins(100, 70, 0, 0)
textView.setTextColor(Color.BLACK)
textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18f)
for (element in arr) {
textView.append(element + 'n')
}
textView.layoutParams = params
linear?.addView(textView)

我试图在循环中的ntrisicbounds中添加textView.setbackgrounddrawable,但只显示一个

试试这个:

textView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.image, 0, 0, 0);

在xml文件中尝试此操作:

<TextView
android:id="@+id/textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:drawableLeft="@drawable/image"
android:drawablePadding="5dp"
android:singleLine="true"
/>

此外,请查看官方文件-https://developer.android.com/reference/android/widget/TextView#setCompoundDrawablesWithIntrinsicBounds(int,%20int,%20iint,%20int(

试试这个

for (int i = 0; i <2 ; i++) {
TextView tv = new TextView(this);
tv.setText("testing");
tv.setTextColor(getResources().getColor(R.color.black));
Drawable img = this.getResources().getDrawable(R.drawable.black_humidity_icon);
img.setBounds(0, 0, 60, 60);
tv.setCompoundDrawables(img, null, null, null);
rootLinearLayout.addView(tv);
}

您可以根据需要进行自定义。希望这能满足你的要求。

最新更新