您的位置:首页 > Web前端 > CSS

样式和主题

2016-12-14 21:36 330 查看

6.样式和主题

配置样式

在style文件里设置,如果想继承系统自带的主题或者样式,指定
parent=“需要继承的样式”;如果需要修改继承样式里的某一样,在自定义样式里面重写需要修改的属性即可。

<style name="text_content_style">

    <item name="android:layout_width">match_parent</item>

    <item name="android:layout_height">wrap_content</item>

    <item name="android:textColor">#0000ff</item>

    <item name="android:textSize">20sp</item>

</style>

<style name="text_title_style" parent="@style/text_content_style">

     <item name="android:textSize">25sp</item>

</style>

<!-- 该方式也可以指定父类为text_content_style,但是不建议
-->

<style name="text_content_style.sub">

    <item name="android:textSize">28sp</item>

</style>

这样做的目的是为了达到复用,代码的简洁,统一修改的便捷。
当一个布局界面有大量相同重复的布局属性参数时,就可以使用抽取style的方式来实现,比如:

<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:orientation="vertical"

    tools:context=".MainActivity" >

    

<TextView

        style="@style/text_title_style"

        android:text="@string/hello_world" />

    

    <TextView

        style="@style/text_content_style"

        android:text="@string/hello_world" />

 

    <TextView

        style="@style/text_content_style.sub"

        android:text="@string/hello_world" />

 

    <TextView

        style="@style/text_content_style"

        android:text="@string/hello_world" />

 

    <TextView

        style="@style/text_content_style"

        android:text="@string/hello_world" />

 

    <TextView

        style="@style/text_content_style"

        android:text="@string/hello_world" />

 

</LinearLayout>

设置主题

可以通过设置theme属性参数来修改整个应用程序或者单个界面的主题风格:

在清单文件里面配置 theme="@style:..."

    <application

        android:allowBackup="true"

        android:icon="@drawable/ic_launcher"

        android:label="@string/app_name"

        android:theme="@style/AppTheme"

         >

指定style为AppTheme则整个应用程序的主题风格即为AppTheme的风格,当然也可以修改AppTheme的风格,将当前主题添加一个没有标题栏的风格:

     <!-- Application theme. -->

    <style name="AppTheme" parent="AppBaseTheme">

         <item name="android:windowNoTitle">true</item>

        <!-- All customizations that are NOT specific to a particular API-level can go here. -->

    </style>

或者自己定义一个theme:

    <style name="my_app_theme">

          <item name="android:windowNoTitle">true</item>

          <item name="android:background">#440000ff</item>

</style>

也可以在代码中设置主题:

在代码设置 setTheme(ResId)
此方法必须在setContentView之前调用

public class MainActivity
extends Activity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setTheme(R.style.my_app_theme);

setContentView(R.layout.activity_main);

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: