Reputation: 1105
I have a button with text and a drawable on the left. Is there any way I can make that drawable scale to it's appropriate size (fill button's height) while keeping its aspect ratio?
Relevant excerpt from my layout:
<Button
android:text="@string/add_fav"
android:id="@+id/event_fav_button"
android:layout_width="match_parent"
android:layout_height="40dp"
android:drawableLeft="@drawable/star_yellow"/>
Upvotes: 6
Views: 7205
Reputation: 5566
You can use a function made of following code in onCreate()
:
//get left drawable
Drawable drawable = btn.getCompoundDrawables()[0];
int imgHeight = drawable.getIntrinsicHeight();
int imgWidth = drawable.getIntrinsicWidth();
//for dpToPixel look here: https://stackoverflow.com/a/6327095/2306907
float scale = (float) (dpToPixel(40)) / imgHeight;
Rect rect = drawable.getBounds();
int newWidth = (int)(imgWidth * scale);
int newHeight = (int)(imgHeight * scale);
rect.left = rect.left + (int)(0.5 * (imgWidth - newWidth));
rect.top = rect.top + (int)(0.5 * (imgHeight - newHeight));
rect.right = rect.left + newWidth;
rect.bottom = rect.top + newHeight;
drawable.setBounds(rect);
or have a look at this answer, which tries to give an "universal" solution.
Upvotes: 0
Reputation: 625
Can U create a button (containing all) like that in graphics.
Or U can try with this>> 1. Take a Layout(Relative or Linear) with width and height same as your button size. 2. Now put the image view and text view within that. 3. Make layout clickable..
Upvotes: 0