7.4 自定義樣式
樣式,簡單的來說,是View的一組屬性,通過這個屬性可以方便的定義控件的樣式。接下來,我會具體的通過例子來描述如和使用自定義樣式。
首先,樣式,我們可以知道,它包括了諸如字體、文字顏色等設置。不過,這些只是改變了View的一些屬性,具體的屬性還是得依靠所繪製的View。
使用方式:
1. 定義樣式文件
2. 在view樣式中引用樣式
7.4.1 定義樣式文件
樣式文件存放位置爲res/values/styles.xml
<stylename="textTheme">
<itemname="android:textColor">#F00</item>
<itemname="android:textSize">20sp</item>
</style>
代碼片段7.4.1.1 樣式文件定義
7.4.2 在View中使用樣式
引用
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="@style/textTheme"
android:text="@string/hello_world"/>
代碼片段7.4.2.1 View中引用樣式
7.4.3 樣式的繼承
樣式除了直接使用,也可以當作父類被其他樣式繼承,如下:
<stylename="textTheme">
<itemname="android:textColor">#F00</item>
<itemname="android:textSize">20sp</item>
</style>
<stylename="textThemeDetail"parent="textTheme">
<itemname="android:padding">20dp</item>
</style>
代碼片段7.4.3.1 父類樣式
註釋:可以看到,textThemeDetail樣式,繼承了textTheme的樣式,如果想要使用顏色爲紅色,字體大小爲20,內邊框距離爲20的樣式,可以引用textThemeDetail的樣式。
7.4.4 作爲主題處理
樣式除了作爲View的具體屬性外,還可以作爲主題進行處理。其實,它的本質就是應用於整個屏幕的樣式。
比如,我們定義如下的主題(全屏樣式):
<stylename="AppMyTheme">
<itemname="android:textSize">15sp</item>
</style>
代碼片段7.4.4.1 主題樣式
那麼定義了主題後,如何使用這個主題?
我們有兩種方法:
1. 在onCreate方法中直接調用java使用
package com.example.androidstudy_style;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTheme(R.style.AppMyTheme);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; thisadds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
代碼片段7.4.4.2 java應用主題
除了這種方法,當然還有一種,用xml應用:
<?xmlversion="1.0"encoding="utf-8"?>
<manifestxmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.androidstudy_style"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme">
<activity
android:name="com.example.androidstudy_style.MainActivity"
android:theme="@style/AppMyTheme"
android:label="@string/app_name">
<intent-filter>
<actionandroid:name="android.intent.action.MAIN"/>
<categoryandroid:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>
代碼片段7.4.4.3 xml應用主題
註釋:這個的應用實在Android Manifest配置文件中應用,而不是像使用View中的style一樣是在activity佈局文件中配置。這個是需要注意的地方。
另:xml中只能設置一個主題,而java代碼中,你卻可以通過setTheme的方法設置多個主題來使用。
注意:所有主題的調用,都必須在setContentView方法或inflate方法之前被應用。
7.5 小結
通過Android的各種控件和樣式,可以構建出各種各樣的應用程序。