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

我正在动态创建按钮。我首先使用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);


陪伴而非守候
浏览 739回答 3
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);

天涯尽头无女友

我这样做:&nbsp;// Left, top, right, bottom drawables.&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Drawable[] drawables = button.getCompoundDrawables();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // get left drawable.&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Drawable leftCompoundDrawable = drawables[0];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // get new drawable.&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Drawable img = getContext().getResources().getDrawable(R.drawable.ic_launcher);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // set image size (don't change the size values)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; img.setBounds(leftCompoundDrawable.getBounds());&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // set new drawable&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; button.setCompoundDrawables(img, null, null, null);

aluckdog

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 {&nbsp; &nbsp; defaultConfig {&nbsp; &nbsp; &nbsp; &nbsp; vectorDrawables.useSupportLibrary = true&nbsp; &nbsp; }}在应用程序类中:class MyApplication : Application() {&nbsp; &nbsp; override fun onCreate() {&nbsp; &nbsp; &nbsp; &nbsp; super.onCreate()&nbsp; &nbsp; &nbsp; &nbsp; AppCompatDelegate.setCompatVectorFromResourcesEnabled(true)&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Android
Java