样式是针对View的,比如TextView、Button等控件,主题是针对Activity、整个APP的。
样式、主题是多种属性的集合,类似于网页中的CSS样式,可以让设计与内容分离,并且可以继承、复用,减少了代码量,方便维护、统一管理。
样式、主题都是在 res -> values -> styles.xml 中定义的:
1 <resources> 2 3 <!--这个是基础主题,自带的--> 4 <!-- Base application theme. --> 5 <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar"> 6 <!-- Customize your theme here. --> 7 <item name="colorPrimary">@color/colorPrimary</item> 8 <item name="colorPrimaryDark">@color/colorPrimaryDark</item> 9 <item name="colorAccent">@color/colorAccent</item> 10 </style> 11 12 <!-- 一个style就是一个样式/主题 --> 13 <style name="style1"> 14 <!-- 一个item表示一个属性,属性值不加引号 --> 15 <item name="android:layout_width">match_parent</item> 16 <item name="android:layout_height">wrap_content</item> 17 </style> 18 19 <!-- 样式、主题可以继承--> 20 <style name="style2" parent="style1"> 21 <item name="android:textColor">#FF0000</item> 22 <item name="android:textSize">20sp</item> 23 </style> 24 25 <!--所有自定义的主题都要继承 Theme.AppCompat.Light.DarkActionBar(不会写可以看最上面的那个style),以保证兼容性 --> 26 <style name="theme" parent="Theme.AppCompat.Light.DarkActionBar"> 27 <item name="android:background">@drawable/a</item> 28 </style> 29 30 </resources>
然后就可以在布局的xml文件的某个View中用style属性引用样式:
1 <TextView 2 style="@style/style1" 3 android:text="hello world!" />
在清单文件AndroidManifest.xml中使用theme属性引用主题:
1 <?xml version="1.0" encoding="utf-8"?> 2 <manifest xmlns:android="http://schemas.android.com/apk/res/android" 3 package="com.example.myapplication"> 4 5 <application 6 android:allowBackup="true" 7 android:icon="@mipmap/ic_launcher" 8 android:label="@string/app_name" 9 android:roundIcon="@mipmap/ic_launcher_round" 10 android:supportsRtl="true" 11 android:theme="@style/AppTheme"> <!-- 整个APP的主题--> 12 13 <activity 14 android:name=".MainActivity" 15 android:theme="@style/theme"> <!--这个Activity的主题 --> 16 <intent-filter> 17 <action android:name="android.intent.action.MAIN" /> 18 <category android:name="android.intent.category.LAUNCHER" /> 19 </intent-filter> 20 </activity> 21 22 </application> 23 24 </manifest>
如果背景图片不能占满该控件/Activity,默认会自动填充铺满: