1. 程式人生 > >android studio (主題和樣式)

android studio (主題和樣式)

一、樣式(style)

  在我們編寫android studio  的佈局檔案中,會遇到很多的  重複的程式碼如下,4個TextView中,只有name不一樣,其餘都一樣,感覺挺冗餘的,程式碼量很多,這個我們可以寫在styles.xml中,定義一個styles然後在佈局檔案中引用即可。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="123"
        android:gravity="center_vertical"
        android:textSize="30dp"
        android:drawableLeft="@drawable/ic_launcher_foreground" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="456"
        android:gravity="center_vertical"
        android:textSize="30dp"
        android:drawableLeft="@drawable/ic_launcher_foreground" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="789"
        android:gravity="center_vertical"
        android:textSize="30dp"
        android:drawableLeft="@drawable/ic_launcher_foreground" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="999"
        android:gravity="center_vertical"
        android:textSize="30dp"
        android:drawableLeft="@drawable/ic_launcher_foreground" />



</LinearLayout>

   效果圖

在styles.xml中定義如下:我們建立一個樣式 mystyle    並且把共有的都設定 在一起

在佈局檔案中引用  這個感覺是不是 簡潔多了

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    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/mystyle"
        android:text="123"
     />
    <TextView
        style="@style/mystyle"
        android:text="456"/>
       />
    <TextView
        style="@style/mystyle"
        android:text="789"/>
    <TextView
        style="@style/mystyle"
        android:text="999" />
</LinearLayout>

效果是一樣的。

二、主題(Theme)

     主題也是本質Style     

     在styles中定義但是在manifest.xml中引用

      它是針對於某個應用和某個Activity的介面

   

Styles中設定