为了账号安全,请及时绑定邮箱和手机立即绑定

如何在Android按钮上以编程方式设置drawableLeft?

如何在Android按钮上以编程方式设置drawableLeft?

陪伴而非守候 2019-10-05 11:11:20
我正在动态创建按钮。我首先使用XML设置了样式,然后尝试使用下面的XML并将其编程。<Button    android:id="@+id/buttonIdDoesntMatter"    android:layout_height="wrap_content"    android:layout_width="fill_parent"    android:text="buttonName"    android:drawableLeft="@drawable/imageWillChange"    android:onClick="listener"    android:layout_width="fill_parent"></Button>到目前为止,这就是我所拥有的。除了可绘制对象,我可以做所有事情。linear = (LinearLayout) findViewById(R.id.LinearView);Button button = new Button(this);button.setText("Button");button.setOnClickListener(listener);button.setLayoutParams(    new LayoutParams(        android.view.ViewGroup.LayoutParams.FILL_PARENT,                 android.view.ViewGroup.LayoutParams.WRAP_CONTENT    ));      linear.addView(button);
查看完整描述

3 回答

?
狐的传说

TA贡献1804条经验 获得超3个赞

您可以使用该setCompoundDrawables方法来执行此操作。请参阅此处的示例。我使用了此功能,但未使用,setBounds并且效果良好。您可以尝试任何一种方式。


更新:如果链接断开,请在此处复制代码


Drawable img = getContext().getResources().getDrawable( R.drawable.smiley );

img.setBounds( 0, 0, 60, 60 );

txtVw.setCompoundDrawables( img, null, null, null );

要么


Drawable img = getContext().getResources().getDrawable( R.drawable.smiley );

txtVw.setCompoundDrawablesWithIntrinsicBounds( img, null, null, null);

要么


txtVw.setCompoundDrawablesWithIntrinsicBounds( R.drawable.smiley, 0, 0, 0);


查看完整回答
反对 回复 2019-10-05
?
天涯尽头无女友

TA贡献1831条经验 获得超9个赞

我这样做:


 // Left, top, right, bottom drawables.

            Drawable[] drawables = button.getCompoundDrawables();

            // get left drawable.

            Drawable leftCompoundDrawable = drawables[0];

            // get new drawable.

            Drawable img = getContext().getResources().getDrawable(R.drawable.ic_launcher);

            // set image size (don't change the size values)

            img.setBounds(leftCompoundDrawable.getBounds());

            // set new drawable

            button.setCompoundDrawables(img, null, null, null);


查看完整回答
反对 回复 2019-10-05
?
aluckdog

TA贡献1847条经验 获得超7个赞

Kotlin Version

使用以下代码片段向按钮添加一个可绘制对象:


val drawable = ContextCompat.getDrawable(context, R.drawable.ic_favorite_white_16dp)

button.setCompoundDrawablesWithIntrinsicBounds(drawable, null, null, null)


• Important Point in Using Android Vector Drawable

当您使用可绘制的android vector并希望向21以下的API向后兼容时,请将以下代码添加到:


在应用程序级别build.gradle:


android {

    defaultConfig {

        vectorDrawables.useSupportLibrary = true

    }

}

在应用程序类中:


class MyApplication : Application() {


    override fun onCreate() {

        super.onCreate()


        AppCompatDelegate.setCompatVectorFromResourcesEnabled(true)

    }


}


查看完整回答
反对 回复 2019-10-05
  • 3 回答
  • 0 关注
  • 738 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信