Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (4k points)

I'm dynamically creating buttons. I styled them using XML first, and I'm trying to take the XML below and make it programmatic.

<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 have so far. I can do everything but the drawable.

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

2 Answers

0 votes
by (46k points)

You can try the setCompoundDrawables method to do this. See the pattern here. I used this without applying the setBounds and it ran. You can try both way.

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

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

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

or

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

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

or

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

0 votes
by (1.2k points)

In the code, we have to use `setCompoundDrawablesWithIntrinsicBounds`. This will let us create the buttons programmatically that will consist of drawables on the left side. This method allows you to set the drawable images with a TextView that allows you to place images on left, right, bottom and top of text. Here is the syntax for the same:

public void setCompoundDrawablesWithIntrinsicBounds (int left, int top, int right, int bottom)

Now, these parameters will allow you to set the values for the drawables.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
2 answers
0 votes
1 answer

1.2k questions

2.7k answers

501 comments

693 users

Browse Categories

...