edi233
edi233

Reputation: 3031

Button and drawable left

I create button in xml file like this:

    <Button
        android:id="@+id/call_button"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_marginTop="30dp"
        android:background="@drawable/button"
        android:layout_weight="40" 
        android:drawableLeft="@drawable/symbol_phone"
        android:paddingLeft="20dp"
        android:drawablePadding="-25dp"
        android:text="Call"
        android:textColor="@color/white"
        />

I would like to know how I can do drawableLeft in activity. I know that is stupid but I need do this in activity because I create button there. How I can do the same what I have in xml file in my activity? I need add drawableLeft and drawable padding and padding left. This is how I create button in activity

 Button button1 = new Button(this);
 button1.setLayoutParams(new RelativeLayout.LayoutParams(buttonWidth, buttonHeight));
 button1.setText(systemTexts.getShowCallButton());
 button1.setBackgroundDrawable(new                                      
 button1.setTextColor(Color.parseColor(buttonTextColor));

Upvotes: 7

Views: 20164

Answers (5)

Aj 27
Aj 27

Reputation: 2427

You can try this:

txtVw.setCompoundDrawables(R.drawable.img_nature, 0, 0, 0);

Upvotes: 0

Dhruvil Patel
Dhruvil Patel

Reputation: 2930

Drawable image = getContext().getResources().getDrawable( R.drawable.icon );
image.setBounds( 0, 0, 60, 60 );
button.setCompoundDrawables( image, null, null, null );

do this

Update:

Since getContext().getResources().getDrawable is now deprecated, use this instead:

  Drawable image = ContextCompat.getDrawable(getApplicationContext(),R.drawable.icon);
  image.setBounds( 0, 0, 60, 60 );
  button.setCompoundDrawables( image, null, null, null );

Upvotes: 21

Kirtikumar A.
Kirtikumar A.

Reputation: 4204

You can use below code

<Button android:text="@string/button_label" 
android:id="@+id/buttonId"
android:layout_width="160dip"
android:layout_height="60dip"
android:layout_gravity="center"
android:textSize="13dip"
android:drawableLeft="@drawable/button_icon"
android:drawablePadding="2dip"
android:paddingLeft="30dip"
android:paddingRight="26dip"
android:singleLine="true"
android:gravity="center" />  

It will manage by padding ti text and image both

Upvotes: -1

keyser
keyser

Reputation: 19189

The way to programmatically set drawableLeft is with setCompoundDrawablesWithIntrinsicBounds.

You can set the padding with setPadding

The docs show the corresponding java method for all xml tags.

Upvotes: 2

user370305
user370305

Reputation: 109247

Try this,

Drawable icon= getContext().getResources().getDrawable(R.drawable.icon);
button.setCompoundDrawablesWithIntrinsicBounds(icon, null, null, null);

Upvotes: 5

Related Questions