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

1 Answer

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

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Oct 15, 2019 in Java by Shubham (3.9k points)
0 votes
1 answer

Browse Categories

...