上篇我们知道了怎么改变TextView标签的各种属性,问题是,如果页面上有几十个上百个同类标签,难道要一个一个的修改吗?马上想到了CSS样式表,这里要庆幸的是Android同样支持样式表的加载。
简单来说只涉及两类文件:layout/main.xml、values/style.xml,下面是他们各自的代码:
main.xml
<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" > <TextView style="@style/firstStyle" android:id="@+id/firstText" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/hello_world" /> </LinearLayout>
<resources xmlns:android="http://schemas.android.com/apk/res/android"> <style name="firstStyle"> <item name="android:textSize">18sp</item> <item name="android:textColor">#FF00FF</item> </style> </resources>
package com.dy.study.firstbase; import android.os.Bundle; import android.app.Activity; public class Main extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } }
再对比一下,把样式表的颜色改为#00FFFF,再看下效果:
样式表简单介绍到这里,接着说color.xml,由于系统提供的Color.GREEN等之类的太少太单薄,所以为了美化UI,还是自己定义多个颜色代码方便使用吧,至于color.xml里面的内容,网上一搜一堆,我在学习的时候就是借鉴其他人共享的资料,这里感谢一下分享者,言归正传,简单列举几个颜色代码,并在main.java里面调用,看看效果:
color.xml
<resources> <color name="pink">#ffc0cb</color> <!-- 粉红色 --> <color name="white">#ffffff</color> <!-- 白色 --> <color name="gold">#ffd700</color> <!-- 金色 --> <color name="indianred">#cd5c5c</color> <!-- 印第安红 --> <color name="mediumvioletred">#c71585</color> <!-- 中紫罗兰色 --> </resources>
package com.dy.study.firstbase; import android.os.Bundle; import android.widget.Button; import android.widget.TextView; import android.app.Activity; public class Main extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); findViews(); change(); } private TextView firstText; private Button firstButton; private void findViews(){ firstText=(TextView)findViewById(R.id.firstText); firstButton=(Button)findViewById(R.id.firstButton); } private void change(){ firstText.setTextColor(getResources().getColor(R.color.gold)); firstButton.setTextColor(getResources().getColor(R.color.indianred)); } }
main.xml
<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" > <TextView android:id="@+id/firstText" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/hello_world" /> <Button android:id="@+id/firstButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/demo" /> </LinearLayout>
然后看看显示结果:
这里需要注意的是,获取颜色信息需要使用getResources().getColor(R.color.gold)格式。样式表和color文件说完了,愿大家都有一个多彩靓丽的生活。