java 代码设置drawableTop
时间: 2023-08-09 16:06:26 浏览: 45
要在 Java 代码中设置 Drawable 的位置,可以使用 `setCompoundDrawablesWithIntrinsicBounds()` 方法。以下是一个示例:
```java
TextView textView = findViewById(R.id.my_text_view);
Drawable drawable = getResources().getDrawable(R.drawable.my_drawable);
textView.setCompoundDrawablesWithIntrinsicBounds(null, drawable, null, null);
```
在这个示例中,我们首先获取一个 TextView 对象,并使用 `getResources()` 方法获取 Drawable 对象。然后我们使用 `setCompoundDrawablesWithIntrinsicBounds()` 方法将 Drawable 设置为 TextView 的顶部。这个方法接受四个参数,分别对应 Drawable 的左、上、右、下四个位置,如果想要设置其他位置可以传入其他参数。
注意,这个方法中的第一个参数是 `null`,因为我们不需要设置 Drawable 的左边。如果你想设置 Drawable 的其他位置,可以将其他参数设置为相应的 Drawable 对象或 `null`。例如,如果你想在 TextView 的左侧设置 Drawable,可以这样写:
```java
textView.setCompoundDrawablesWithIntrinsicBounds(drawable, null, null, null);
```
这将在 TextView 的左侧设置一个 Drawable,其他位置不变。