Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to specify border in android button?

Tags:

android

button

Is it possible to specify border in Android button in the main.xml? [p.s. without the 'separate xml file containing stroke tag' but in the original file where I define the button and also without the 'dynamically by programming' solution and 'images' solution]

  <Button
    android:background="#FFFFFF"
    android:layout_width="0dp"
    android:layout_height="fill_parent"
    android:text="Player 3"
    android:layout_x="0px"
    android:layout_y="0px"
    android:id="@+id/p3"
    android:layout_weight="1" 

/>  

here I am changing the background dynamically but the problem is, for 2 buttons there is no border.

like image 961
Nyx Avatar asked Jul 10 '13 07:07

Nyx


Video Answer


2 Answers

Try to use shape

my_shape.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >

    <corners
        android:bottomLeftRadius="7dp"
        android:bottomRightRadius="7dp"
        android:radius="0.1dp"
        android:topLeftRadius="7dp"
        android:topRightRadius="7dp" />

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

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

</shape>

And Button

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/my_shape"
    android:text="Button" />

Screenshot

enter image description here

I hope this will help you.

like image 86
Gunaseelan Avatar answered Oct 05 '22 03:10

Gunaseelan


This is not the recommended way to do it because it causes overdraw and adds unnecessary views, Gunaseelan has the proper method.


There's no concept of borders as an attribute. The accepted way is to use a separate drawable as the background to the View (using stroke as you've mentioned and as @gunaseelan writes).

The other (not recommended) way is to enclose your Button in another View like a LinearLayout, set the background color to the desired border colour on the encapsulating View and padding on the outer View too.

<LinearLayout
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:background="#342334"
    android:padding="5dp"
    >
    <Button
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:text="whatwhaaat"
        />
</LinearLayout>

The value of the padding will indicate the thickness of the border. This method is not recommended as you end up with an extra View in your layout, and another layer of overdraw (it draws the LinearLayout then the Button on top).

like image 30
ataulm Avatar answered Oct 05 '22 03:10

ataulm