一、样式(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中设置



本文详细介绍如何在Android开发中使用样式(style)和主题(Theme)来减少重复代码,提高布局文件的可读性和维护性。通过实例展示如何定义和引用样式,以及在styles.xml中设置主题,应用于整个应用或特定Activity。
9558

被折叠的 条评论
为什么被折叠?



