android studio (主题和样式)

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

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

     

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

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值