Android 成长笔记

Android 资源简介(八) Style 资源

2017-04-08  本文已影响16人  赵者也

一个样式相当于多个属性设置的集合,其他 UI 组件通过 style 属性来指定样式,这就相当于把该样式包含的所有属性设置同时应用于该 UI 组件。

Android 的样式资源文件放在 /res/values 目录下,样式资源文件的根元素是 <resources>,该元素可以包含多个 <style> 子元素,每个 <style> 定义一个样式。<style> 可以指定如下两个属性:

  1. name:指定样式的名称。
  2. parent: 指定样式所继承的父样式。

<style> 元素内部可以包含多个 <item> 元素,每个 <item> 元素定义一个格式项。

下面是一个简单的使用示例,首先是自定义的 Style 内容,将它加在 /res/values 目录下的 styles.xml 文件中:

<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->

        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

    <style name="test_style01">
        <item name="android:textSize">20sp</item>
        <item name="android:textColor">@color/colorPrimaryDark</item>
    </style>

    <style name="test_style02" parent="@style/test_style01">
        <item name="android:background">#EEEE66</item>
        <item name="android:padding">8dp</item>
        <item name="android:textColor">#000000</item>
    </style>
</resources>

主布局文件的内容如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorGray"
    android:orientation="vertical"
    android:id="@+id/container"
    >

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:text="@string/testStyle01"
        style="@style/test_style01"
        />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:text="@string/testStyle02"
        style="@style/test_style02"
        />

</LinearLayout>

主程序文件的代码:

package com.toby.personal.testlistview;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    final private static String TAG = "Toby_Test";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

程序的运行效果:


运行效果

参考文献:《疯狂Android讲义(第2版)》

上一篇 下一篇

猜你喜欢

热点阅读