一:样式和主题
1.系统自带的主题和样式(已上传)
2.自定义主题和样式---自定义样式和主题的步骤如下:
在res/values 目录创建样式文件mystyle.xml,添加<resources> 根节点。------->在<resources>节点中添加一个<style>节点,并在该节点中为样式或主题定义一个名称。------->在<style>节点中声明一个或多个<item>,每个<item>节点需要定义一个属性名,并在元素内部设置这个属性的值。
1.系统自带的主题和样式(已上传)
2.自定义主题和样式---自定义样式和主题的步骤如下:
在res/values 目录创建样式文件mystyle.xml,添加<resources> 根节点。------->在<resources>节点中添加一个<style>节点,并在该节点中为样式或主题定义一个名称。------->在<style>节点中声明一个或多个<item>,每个<item>节点需要定义一个属性名,并在元素内部设置这个属性的值。
代码如下:
(1).新建一个文件mystyle.xml---设置样式与主题
<?xml version="1.0" encoding="utf-8"?> <resources> <style name="TextStyle" > <item name="android:layout_width">wrap_content</item> <item name="android:layout_height">wrap_content</item> <item name="android:textSize">30dp</item> <item name="android:textColor">#990033</item> </style> <style name="MyTheme"> <item name="android:background">#D9D9D9</item> </style> </resources>
(2).在activity_main.xml中添加样式文本,代码如下,运行
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:text="自定义样式" style="@style/TextStyle" android:layout_centerInParent="true" /> </RelativeLayout>
(3).在AndroidManifest中修改为我们设置的主题,代码、运行如下(android:theme="@style/MyTheme")--报错原因如下已解释
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.yuekang.demo1"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:theme="@style/MyTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
解决方法
a.如果改成上篇文章的android:theme="@style/Theme.AppCompat.Dialog",也能正常运行,但结果就不是我们自己设置的主题了(放弃)
b.Android studio中MainActivity中修改继承的对象默认为AppCompatActivity,将其修改为为Activity后,如图-我们在mystyle中设置的主题背景颜色为灰色,运行成功。