How do I set the drawableLeft on the Android button with the code?

Asked 2 years ago, Updated 2 years ago, 111 views

I make buttons dynamically. First, I set the style to xml like below, but I want to transfer it to the code.

<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>

This is what I want, but it's not easy to do it with the code below.

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);

android android-layout java android-2.2-froyo

2022-09-22 22:26

1 Answers

You can use the setCompoundDrawable method.

1.

Drawable img = getContext().getResources().getDrawable( R.drawable.smiley );
img.setBounds( 0, 0, 60, 60 );
txtVw.setCompoundDrawables( img, null, null, null );

2.

Drawable img = getContext().getResources().getDrawable( R.drawable.smiley );
txtVw.setCompoundDrawablesWithIntrinsicBounds( img, null, null, null);

3. txtVw.setCompoundDrawablesWithIntrinsicBounds( R.drawable.smiley, 0, 0, 0); You can write it like this.


2022-09-22 22:26

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.