Android Rounded Corner TextView

In this post we will see how to add rounded corner to TextView using drawable 

1. Colors


 Define color attritube in color.xml  which will be used in drawable below.


file : colors.xml
<resources>
  
  <color name="button_bgcolor">#EEEEEE</color>
  <color name="button_bgcolor_press">#2e89b1</color>
  <color name="button_bgcolor_enable">#3db5ea</color>

</resources>


2. Drawable


 Create Drawable add selector and assign color to item for different state ( enable, pressed )

file : rounded_corner.xml
<?xml version="1.0" encoding="UTF-8"?>
<selector 
    xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_enabled="false">
        <shape>
            <corners android:radius="22dp" />
            <solid android:color="@color/button_bgcolor" />
        </shape>
    </item>

    <!-- State Pressed-->
    <item android:state_pressed="true">
        <shape>
            <corners android:radius="22dp" />
            <solid android:color="@color/button_bgcolor_press" />
        </shape>
    </item>

    <!-- State Enabled -->
    <item android:state_enabled="true">
        <shape>
            <corners android:radius="22dp" />
            <solid android:color="@color/button_bgcolor_enable" />
        </shape>
    </item>

</selector>


3. XML Layout


Create XML Layout , add TextView and set the background of TextView with above defined drawable .

file : activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical"
    android:padding="40dp"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/rounded_corner"
        android:clickable="true"
        android:focusable="true"
        android:gravity="center"
        android:padding="10dp"
        android:text="Hello World!"
        android:textColor="@color/white"
        android:textSize="22sp" />

</LinearLayout>



No comments:

Post a Comment