Android性能优化之布局优化

本文介绍了几种有效的Android UI布局优化方法,包括合理选择RelativeLayout和LinearLayout,利用include标签复用公共布局,采用ViewStub按需加载布局,以及使用merge标签减少布局嵌套层次。

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

1、布局原则

1.1、使用RelativeLayout和LinearLayout

尽量多使用RelativeLayoutLinearLayout

在布局层次一样的情况下,建议使用LinearLayout代替RelativeLayout(因为LinearLayout性能要稍高一点);

在结构层次复杂的时候建议使用RelativeLayout(因为RelativeLayout简单实现LinearLayout嵌套才能实现的布局)。

1.2、使用include标签

将布局中公用的部分抽取出来并通过include标签引用;

开发中会遇到一些共用的UI组件,比如带返回按钮的导航栏,如果为每一个xml文件都设置这部分布局,一是重复的工作量大,二是如果有变更,那么每一个xml文件都得修改。因此我们可以将这些共用的组件抽取出来单独放到一个xml文件中,然后使用include标签导入共用布局。

下面在一个布局main.xml中用include引入另一个布局titlebar.xml为例。

//titlebar.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="wrap_content"
    android:background="@drawable/mmtitle_bg_alpha" >
 
    <Button
        android:id="@+id/button"
        android:layout_width="75.0dip"
        android:layout_height="40dp"
        android:layout_centerVertical="true"
        android:layout_marginLeft="2dip"
        android:text="返回" />
 
    <TextView
        android:id="@+id/text"
        android:textColor="#ffffff"
         android:layout_alignBaseline="@id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:gravity="center_vertical"
        android:text="@string/app_name"
        android:textSize="20dp" />
</RelativeLayout>

以上定义公用布局titlebar然后在需要引入标题栏的布局main.xml中通过include导入这个共用布局

//main.xml
 
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >
 
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />
 
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
 
        <include layout="@layout/titlebar" />
    </RelativeLayout>
 
</FrameLayout>

1.3、使用ViewStub标签

viewstub标签同include标签一样可以用来引入一个外部布局,但viewstub引入的布局默认不会扩张,即既不会占用显示也不会占用位置,从而在解析layout时节省cpu和内存。 

viewstub常用来引入那些默认不会显示,只在特殊情况下显示的布局,如进度布局、网络失败显示的刷新布局、信息出错出现的提示布局等。

如创建一个error的布局文件显示网络错误的提示信息,如下:

<?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:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:background="@android:color/white"
        android:padding="10dip"
        android:text="Message"
        android:textColor="@android:color/black" />
 
</RelativeLayout>

然后在main.xml里面加入ViewStub的标签引入上面的布局,修改main.xml文件如下:

<merge xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
 
    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
 
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/hello_world" />
 
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent" >
 
            <include layout="@layout/titlebar" />
        </RelativeLayout>
 
        <ViewStub
            android:id="@+id/error_layout"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout="@layout/error" />
    </FrameLayout>
 
</merge>

java代码中通过(ViewStub)findViewById(id)找到ViewStub,通过stub.inflate()展开ViewStub,然后得到子View,如下:

private View errorView;

	private void showError() {
		// not repeated infalte
		if (errorView != null) {
			errorView.setVisibility(View.VISIBLE);
			return;
		}

		ViewStub stub = (ViewStub) findViewById(R.id.error_layout);
		errorView = stub.inflate();
	}

	private void showContent() {
		if (errorView != null) {
			errorView.setVisibility(View.GONE);
		}
	}

1.4、使用merge标签 

merge标签的作用是合并UI布局,使用该标签能降低UI布局的嵌套层次。merge标签可用于两种典型情况:

1布局根结点是FrameLayout且不需要设置backgroundpadding等属性,可以用merge代替,因为Activity内容布局的parent view就是个FrameLayout,所以可以用merge消除只剩一个,这一点可以从上图中看到。

//main.xml
 
<merge xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
 
    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
 
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/hello_world" />
 
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent" >
 
            <include layout="@layout/titlebar" />
        </RelativeLayout>
    </FrameLayout>
 
</merge>

2)某布局作为子布局被其他布局include时,使用merge当作该布局的顶节点,这样在被引入时顶结点会自动被忽略,而将其子节点全部合并到主布局中。

如:foot.xml布局文件中,将原本是RelativeLayout改成merge

<merge xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
 
    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="@dimen/dp_40"
        android:layout_above="@+id/text"/>
 
    <TextView
        android:id="@+id/text"
        android:layout_width="match_parent"
        android:layout_height="@dimen/dp_40"
        android:layout_alignParentBottom="true"
        android:text="@string/app_name" />
 
</merge>

然后布局main.xml中使用include标签引用再引用该foot.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" >
 
    <ListView
        android:id="@+id/simple_list_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginBottom="@dimen/dp_80" />
 
    <include layout="@layout/foot.xml" />
 
</RelativeLayout>

这样,main.xml文件中就不会有多余的Relativelayout布局了,而是直接将foot布局中的buttontextview直接加入根布局中。

 

 

### 使用PyTorch加载CIFAR-10数据集进行图像分类 为了使用PyTorch加载CIFAR-10数据集并执行图像分类任务,通常会遵循一系列特定的操作流程。这些操作包括但不限于导入必要的库、定义转换函数、设置数据加载器以及准备用于训练和测试的数据。 #### 导入所需模块 首先,需要引入一些基本的Python包来辅助完成整个过程: ```python import torch from torchvision import datasets, transforms from torch.utils.data import DataLoader ``` #### 定义图像预处理变换 接着,创建一组适用于输入图片的转换规则,这有助于提高模型性能或加速收敛速度。对于CIFAR-10而言,常见的做法是对原始RGB像素值做标准化处理,并随机裁剪及水平翻转增强样本多样性: ```python transform_train = transforms.Compose([ transforms.RandomCrop(32, padding=4), transforms.RandomHorizontalFlip(), transforms.ToTensor(), transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)), ]) transform_test = transforms.Compose([ transforms.ToTensor(), transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)), ]) ``` 这里`transforms.Normalize()`中的参数分别代表均值(mean)与标准差(std),它们来源于CIFAR-10官方给出的经验数值[^1]。 #### 设置数据加载器 之后,利用上述配置好的转换对象实例化对应的`datasets.CIFAR10`类,并通过`DataLoader`构建迭代器以便后续批量获取批次(batch)形式的数据供网络学习之用: ```python trainset = datasets.CIFAR10(root='./data', train=True, download=True, transform=transform_train) trainloader = DataLoader(trainset, batch_size=128, shuffle=True, num_workers=2) testset = datasets.CIFAR10(root='./data', train=False, download=True, transform=transform_test) testloader = DataLoader(testset, batch_size=100, shuffle=False, num_workers=2) ``` 以上代码片段展示了如何基于PyTorch框架高效便捷地加载CIFAR-10数据集,并为其指定恰当的前处理方式以适应具体的机器学习应用场景需求[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值