用drawable定义颜色常数的方法
首先定义好资源,然后再Layout中布局,注意尽量全部用可视化布局:
这里定义了一个柠檬色作为textview的颜色,还有一个白色的背景,主要说明一点,就是在添加背景颜色的时候,点击backqround后的按钮选择即可。
如果是把textview的背景变色,用的是如图所示,但是要是改变文字本身颜色,要用的是下面的textcolor
xml代码:
<RelativeLayout 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:background="@color/white_bg"
android:clickable="false"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="54dp"
android:layout_marginTop="137dp"
android:background="@color/ningmeng_text"
android:text="TextView" />
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@+id/textView1"
android:layout_marginLeft="26dp"
android:layout_toRightOf="@+id/textView1"
android:ems="10" >
<requestFocus />
</EditText>
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toLeftOf="@+id/editText1"
android:background="@color/ningmeng_text"
android:text="TextView" />
<EditText
android:id="@+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/textView2"
android:layout_alignBottom="@+id/textView2"
android:layout_alignLeft="@+id/editText1"
android:layout_marginLeft="14dp"
android:ems="10" />
</RelativeLayout>
java代码默认:
运行结果为:
引用Drawable颜色常数及后台
在Oncreate()方法中通过程序描述的方法,实时改变原来TextView的后台色以及文字颜色,要学会用默认的颜色常数来更改文字的前景色。
Resources resources = getBaseContext().getResources();
Drawable Hippo = resources.getDrawable(R.drawable.danzise);//在做这步的时候,遇到点问题,就是找不到danzise这个颜色,原来这个颜色在添加的时候是要加到Drawable中的
textview1 = (TextView)findViewById(R.id.textView1);
//textview1.setBackgroundDrawable(Hippo);
textview1.setBackground(Hippo);
textview2 = (TextView)findViewById(R.id.textView2);
textview2.setTextColor(Color.MAGENTA);
创建Resources和Drawable的对象,调用方法更改背景和文字颜色
在程序中使用了Color.MANGENTA让TextView里的文字变成粉红色,实际上,在Android里还定义了一下12种常见的颜色: