UIDevice类提供了4个(实际只有3个)关于Hierarchy(布局层次关系)的接口。
先列举一下接口。
(1)public void setCompressedLayoutHeirarchy(boolean compressed)
(2)public void dumpWindowHierarchy(File dest) throws IOException
(3)public void dumpWindowHierarchy(OutputStream out) throws IOException
(4)public void dumpWindowHierarchy(String fileName)
对于方法(4),官方已抛弃,不再使用。建议使用方法(2)(3)代替。
通过查看方法(2)的源码,可以发现,其实质是对方法(3)的调用。
而方法(1),则是用于决定是否启动布局压缩。其功能,跟UIautomatorView的工具栏的两个按钮相互对应。右边按钮为压缩按钮。
我们通过实例,调用方法(1)(2),压缩前后,布局的不同。
核心代码如下:
public class HierarchyTest extends UIDeviceTest {
private String path;
private void init(){
Context context= InstrumentationRegistry.getTargetContext();
path=context.getExternalCacheDir().getPath();
Log.i(TAG, "init: path = " + path);
}
@Test
public void TestCase1(){
init();
dumpWindowHierarchy(false,"1.xml");
dumpWindowHierarchy(true,"2.xml");
}
private void dumpWindowHierarchy(boolean pressed, String fileName){
mDevice.setCompressedLayoutHeirarchy(pressed);
Log.i(TAG, "TestCase1: set Compressed Layout Heirarchy to "+pressed);
File file=new File(path,fileName);
try {
if (!file.exists()){
file.createNewFile();
}
mDevice.dumpWindowHierarchy(file);
} catch (IOException e) {
e.printStackTrace();
}
mDevice.waitForIdle();
Log.i(TAG, "file path = "+file.getPath());
}
}
执行结果如下:
I/com.breakloop.u2demo.uidevice.HierarchyTest: init: path = /storage/emulated/0/Android/data/com.breakloop.u2demo/cache
I/com.breakloop.u2demo.uidevice.HierarchyTest: TestCase1: set Compressed Layout Heirarchy to false
I/com.breakloop.u2demo.uidevice.HierarchyTest: file path = /storage/emulated/0/Android/data/com.breakloop.u2demo/cache/1.xml
I/com.breakloop.u2demo.uidevice.HierarchyTest: TestCase1: set Compressed Layout Heirarchy to true
I/com.breakloop.u2demo.uidevice.HierarchyTest: file path = /storage/emulated/0/Android/data/com.breakloop.u2demo/cache/2.xml
使用adb将文件导出。
对比1.xml和2.xml,可以发现,未折叠布局(1.xml)比折叠布局(2.xml)包含信息更详细,但都是与用户交互无关的布局信息。