0%

按XML格式打印view和它的子view

逻辑很简单,就是递归就结束了,很麻烦的是xml的格式调整,换行和缩进花了很久。没有要求写文件,不过写了看看效果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
View view = findViewById(R.id.layout);
ViewGroup viewGroup = (ViewGroup) getWindow().getDecorView();

String str = printViewHierarchy(viewGroup);
writeFile(str);
}

private String printViewHierarchy(ViewGroup viewGroup) {
String lineStarter = "";
String blank = " ";
StringBuilder builder = new StringBuilder();
builder.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
builder.append("\n");
travelView(viewGroup, builder, lineStarter, blank);
return builder.toString();
}

private void writeFile(String str) {
File output = new File(Environment.getExternalStorageDirectory(), "treeView.xml");
if (output.exists()) {
output.delete();
}
try {
FileOutputStream outputStream = new FileOutputStream(output);
outputStream.write(str.getBytes());
outputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
}

public void travelView(View view, StringBuilder builder, String lineStarter, String blank) {
if (view instanceof ViewGroup) {
ViewGroup viewGroup = ((ViewGroup) view);
builder.append(getStartTag(lineStarter, view));
if (viewGroup.getChildCount() != 0) {
builder.append("\n");
}
boolean newLine = true;
for (int i = 0; i < viewGroup.getChildCount(); i++) {
View child = viewGroup.getChildAt(i);
if (newLine) {
lineStarter += blank;
newLine = false;
}
travelView(child, builder,lineStarter,blank);
}
if (viewGroup.getChildCount() != 0) {
lineStarter = lineStarter.substring(0, lineStarter.length() - blank.length());
builder.append(getEndTag(lineStarter, view));
} else {
builder.append(getEndTag(" ", view));
}
} else {
builder.append(getStartTag(lineStarter, view));
builder.append(getEndTag(" ", view));
}
}

private String getEndTag(String pre, View view) {
return (pre + "</" + getViewName(view) + ">" + "\n");
}

private String getStartTag(String pre, View view) {
return (pre + "<" + getViewName(view) + ">");
}

private String getViewName(View view) {
String s = view.toString();
int index = s.indexOf("{");
index = (index == -1) ? s.length() : index;
s = s.subSequence(0, index).toString();
int start = s.lastIndexOf(".");
if (start != -1) {
s = s.substring(start + 1);
}
return s;
}