Working with Buttons


Hai friends, Today we are going to learn how to use buttons in android. We can add buttons in three ways, first one button that contain only text, second one button that contain only image(image button) and third one that contain both text and image.

This is how our android application looks like;

Project Structure;

N B;1.we adding a image called "backup_black.png" in the drawable folder.
2.You can change image position using "android:drawableLeft" (line no 45).

activity_main.xml
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.https://goo.gl/sBYxkW.workingwithbuttons.MainActivity">


    //button with text
    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="50dp"
        android:layout_marginStart="50dp"
        android:layout_marginTop="46dp"
        android:text="backup" />

    //button with image
    <ImageButton
        android:id="@+id/imageButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignEnd="@+id/button"
        android:layout_alignRight="@+id/button"
        android:layout_below="@+id/button"
        android:layout_marginEnd="15dp"
        android:layout_marginRight="15dp"
        android:layout_marginTop="41dp"
        app:srcCompat="@drawable/backup_black" />

    //button with image and text
    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignEnd="@+id/button"
        android:layout_alignRight="@+id/button"
        android:layout_below="@+id/imageButton"
        android:layout_marginTop="50dp"
        android:text="backup"
        android:drawableLeft="@drawable/backup_black"/>

</RelativeLayout>


You can download app from here;


You can download full source code of this tutorial here;





Thanks for your comment