Define color drawable in XML

Define color drawable in XML

We can define our custom color in XML under /res/values/ folder.

example: /res/values/myresources.xml
<resources>
<drawable name="red_color">#ff0000</drawable>
<drawable name="blue_color">#0000ff</drawable>
<drawable name="green_color">#00ff00</drawable>
</resources>


After color defined, it can be acccessed as drawable in XML or using Java code.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="RED in XML"
android:background="@drawable/red_color" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="GREEN in XML"
android:background="@drawable/green_color" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="BLUE in XML"
android:background="@drawable/blue_color" />
<TextView
android:id="@+id/javared"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="RED using Java"/>
<TextView
android:id="@+id/javagreen"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="GREEN using Java"/>
<TextView
android:id="@+id/javablue"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="BLUE using Java"/>
</LinearLayout>


package com.AndroidTestResources;

import android.app.Activity;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.widget.TextView;

public class AndroidTestResourcesActivity extends Activity {

TextView javaRed, javaGreen, javaBlue;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

javaRed = (TextView)findViewById(R.id.javared);
javaGreen = (TextView)findViewById(R.id.javagreen);
javaBlue = (TextView)findViewById(R.id.javablue);

ColorDrawable red = (ColorDrawable)getResources().getDrawable(R.drawable.red_color);
ColorDrawable green = (ColorDrawable)getResources().getDrawable(R.drawable.green_color);
ColorDrawable blue = (ColorDrawable)getResources().getDrawable(R.drawable.blue_color);

javaRed.setBackgroundDrawable(red);
javaGreen.setBackgroundDrawable(green);
javaBlue.setBackgroundDrawable(blue);
}
}



Related: Using shape to define round drawable



0 Response to "Define color drawable in XML"

Posting Komentar