How to set property “android:drawableTop” of a but

2019-01-13 12:08发布

How to set property "android:drawableTop" of a button at runtime

7条回答
做自己的国王
2楼-- · 2019-01-13 12:25
 btn.setBackgroundResource(R.drawable.your_image_name_here);
查看更多
小情绪 Triste *
3楼-- · 2019-01-13 12:27
Drawable top = getResources().getDrawable(R.drawable.image);
button.setCompoundDrawablesWithIntrinsicBounds(null, top , null, null);
查看更多
老娘就宠你
4楼-- · 2019-01-13 12:31
        Button button = (Button) findViewById(R.id.button);
        button.setCompoundDrawables(left, top, right, bottom);
查看更多
家丑人穷心不美
5楼-- · 2019-01-13 12:40

If you are using Kotlin, you can use extension method to make things look elegant.

fun TextView.setDrawableTop(iconId: Int) {
    val icon = this.context?.resources?.getDrawable(iconId)
    this.setCompoundDrawablesWithIntrinsicBounds(null, icon, null, null)
}

Then you can use it like this:

// myTextView: TextView
myTextView.setDrawableTop(R.drawable.ic_happy)
查看更多
地球回转人心会变
6楼-- · 2019-01-13 12:42

Use

button.setCompoundDrawablesWithIntrinsicBounds(left, top, right, bottom);

Sets the Drawables (if any) to appear to the left of, above, to the right of, and below the text. Use 0 if you do not want a Drawable there. The Drawables' bounds will be set to their intrinsic bounds.

If you use

button.setCompoundDrawables(left, top, right, bottom);

Sets the Drawables (if any) to appear to the left of, above, to the right of, and below the text. Use null if you do not want a Drawable there. The Drawables must already have had setBounds(Rect) called.

查看更多
太酷不给撩
7楼-- · 2019-01-13 12:45
final Drawable drawableTop = getResources().getDrawable(R.drawable.btn_check_buttonless_on);

btnByCust.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {


 btnByCust.setCompoundDrawablesWithIntrinsicBounds(null, drawableTop , null, null);

        }
    });
查看更多
登录 后发表回答