Yos*_*ssi 6 android android-layout
调试我的应用程序在三星手机上的奇怪结果,我没有物理访问权限.我想请用户运行一个已检测的应用程序来帮助调试.我的应用程序获得了view一个未知(对我来说) - 层次结构(ViewGroups等).有没有办法"走" View并打印到字符串/其中的ddms所有组件View(ViewGroups等等)?
这类似于HierarchyViewer工具 - 如果我有adb对设备的级别访问权限.
更新:我想我可以使用这个方法
void dumpViewHierarchyWithProperties(Context context, ViewGroup group, BufferedWriter out, int level)
Run Code Online (Sandbox Code Playgroud)
来自ViewDebug.javaAndroid OS来源......
谁有更好的主意?
谢谢!
小智 34
这是我刚为此目的制作的效用函数:
public static void printViewHierarchy(ViewGroup vg, String prefix) {
for (int i = 0; i < vg.getChildCount(); i++) {
View v = vg.getChildAt(i);
String desc = prefix + " | " + "[" + i + "/" + (vg.getChildCount()-1) + "] "+ v.getClass().getSimpleName() + " " + v.getId();
Log.v("x", desc);
if (v instanceof ViewGroup) {
printViewHierarchy((ViewGroup)v, desc);
}
}
}
Run Code Online (Sandbox Code Playgroud)
Ole*_*ndr 12
我创建了实用程序方法,它以一种漂亮的打印方式返回层次结构,并带有人类可读的视图ID.以下是输出示例:
[LinearLayout] no_id
[CardView] com.example:id/card_view
[RelativeLayout] no_id
[LinearLayout] com.example:id/image_container
[AppCompatImageView] com.example:id/incident_icon
[CustomTextView] com.example:id/road_number
[RelativeLayout] no_id
[CustomTextView] com.example:id/distance_to_user
[CustomTextView] com.example:id/obstruction_title
[CustomTextView] com.example:id/road_direction
[CustomTextView] com.example:id/obstruction_description
[AppCompatImageView] com.example:id/security_related
Run Code Online (Sandbox Code Playgroud)
这是实用方法:
public static String getViewHierarchy(@NonNull View v) {
StringBuilder desc = new StringBuilder();
getViewHierarchy(v, desc, 0);
return desc.toString();
}
private static void getViewHierarchy(View v, StringBuilder desc, int margin) {
desc.append(getViewMessage(v, margin));
if (v instanceof ViewGroup) {
margin++;
ViewGroup vg = (ViewGroup) v;
for (int i = 0; i < vg.getChildCount(); i++) {
getViewHierarchy(vg.getChildAt(i), desc, margin);
}
}
}
private static String getViewMessage(View v, int marginOffset) {
String repeated = new String(new char[marginOffset]).replace("\0", " ");
try {
String resourceId = v.getResources() != null ? (v.getId() > 0 ? v.getResources().getResourceName(v.getId()) : "no_id") : "no_resources";
return repeated + "[" + v.getClass().getSimpleName() + "] " + resourceId + "\n";
} catch (Resources.NotFoundException e) {
return repeated + "[" + v.getClass().getSimpleName() + "] name_not_found\n";
}
}
Run Code Online (Sandbox Code Playgroud)
提示:我们使用此方法将视图层次结构添加到某些崩溃报告中.在某些情况下,这确实很有帮助.
| 归档时间: |
|
| 查看次数: |
5756 次 |
| 最近记录: |