Lenny
Lenny

Reputation: 35

Android: Adding image to button with shape background

I'm new to android and writing my first app at the moment but I struggle with one thing for two days now: I have a button with shape from xml file as a background. Every button exept one will have text on it. The one with image is my headache - I used shape background and put the image in TextView: drawableTop but its size is different from every other button and I need all of them to be exactly the same size. Here is the code:

<LinearLayout

    <Button
        android:id="@+id/ButtonCoffee"
        style="@style/buttonText"
        android:layout_height="wrap_content"
        android:drawableTop="@drawable/coffeepng"
        android:focusable="false"
        android:onClick="loadBreak"
        android:textSize="@dimen/activity_vertical_margin" />

The style I am using for all of the buttons:

<style name="buttonText" parent="@android:style/TextAppearance">
    <item name="android:textColor">#FFFFFF</item>
    <item name="android:textSize">35sp</item>
    <item name="android:typeface">sans</item>
    <item name="android:textStyle">bold</item>
    <item name="android:background">@drawable/btn_background_green</item>
    <item name="android:layout_width">match_parent</item>
    <item name="android:layout_marginTop"> 5dp </item>
    <item name="android:layout_marginBottom">5dp </item>
</style>

At the same time I'd like to ask few more question I came up while developing this app:

  1. Is it more efficient to use shape as a button background or is it fine to use png image? Does it matter when it come to same size on different devices?

  2. Is it ok to have many of activities or should I try to draw different sets of my buttons (depending on users style choice) on single activity?

  3. How to pass an image from one activity to another?

Upvotes: 1

Views: 4764

Answers (1)

Hamid Shatu
Hamid Shatu

Reputation: 9700

Create a shape in drawable folder named button_shape.xml as below...

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >

    <solid android:color="#ef4444" />

    <stroke
        android:width="1dp"
        android:color="#992f2f" />

    <corners android:radius="16dp" />

</shape>

Then use this shape to set as background of button as below...

<Button
    android:id="@+id/Button1_2"
    style="@style/buttonText"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:focusable="false"
    android:onClick="load1_2"
    android:text="@string/btn1_2"
    android:drawableTop="@drawable/coffeepng"
    android:background="@drawable/button_shape" />

Upvotes: 1

Related Questions