HierarchyViewer和ViewNode

转自:http://blog.csdn.net/rtczl/article/details/8229780

  上一篇博文讲了通过id找到控件进行相关操作,那么控件的更多信息能不能获取呢?比如控件的width、height、坐标、文本等等。这些就要通过HierarchyViewer和ViewNode类来实现。这里依然以天翼空间为例,接着上一篇博文介绍。

        1、导入模块:输入from com.android.chimpchat.hierarchyviewer import HierarchyViewer,ViewNode,为了方便后续使用,我写成了from com.android.chimpchat.hierarchyviewer import HierarchyViewer as HV和from com.android.hierarchyviewerlib.device import ViewNode as VN两句;

        2、获取HierarchyViewer对象:输入hvT528d=T528d.getHierarchyViewer(),T528d为MonkeyDevice对象,我们可以把HierarchyViewer对象看作是一个界面查看器;

        3、获取ViewNode对象:获取天翼空间流量提示界面的“同意”按钮,输入vnT528d=hvT528d.findViewById("id/btn_agree"),我们可以把ViewNode对象看作是一个控件;

        4、获取控件的width和height:输入vnT528d.width和vnT528d.height即可获取控件的width和height;

        5、获取控件的坐标:输入hvT528d.getAbsoluteCenterOfView(vnT528d)或hvT528d.getAbsolutePositionOfView(vnT528d),前者获取的是控件中点的坐标,后者获取的是控件左上角的坐标;

        6、获取控件的文本:输入hvT528d.getText(vnT528d)。另外之前讲的EasyMonkeyDevice类中也有一个类似方法叫getText(By),不过参数是By对象,并非这里的ViewNode对象。

        由于monkeyrunner是Jython编写的,Jython不支持中文,所以这里我就不写到代码里了,不然会报错,有兴趣的朋友可以找些英文软件来试试。完整代码如下:

[python]  view plain copy
  1. from com.android.monkeyrunner import MonkeyRunner as MR  
  2. from com.android.monkeyrunner import MonkeyDevice as MD  
  3. from com.android.monkeyrunner import MonkeyImage as MI  
  4. from com.android.monkeyrunner.easy import EasyMonkeyDevice,By  
  5. from com.android.chimpchat.hierarchyviewer import HierarchyViewer as HV  
  6. from com.android.hierarchyviewerlib.device import ViewNode as VN  
  7.   
  8. T528d=MR.waitForConnection(10)  
  9. if T528d:  
  10.     print("Connect device successful!")  
  11. else:  
  12.     print("Connect device failed!")  
  13. eT528d=EasyMonkeyDevice(T528d)  
  14. hvT528d=T528d.getHierarchyViewer()  
  15. T528d.installPackage("D:\\MonkeyRunnerDemo\\Apps\\estore.apk")  
  16. T528d.startActivity(component="com.eshore.ezone/.StartActivity")  
  17. MR.sleep(3)  
  18. vnT528d=hvT528d.findViewById("id/btn_agree")  
  19. print("Width: "+str(vnT528d.width))  
  20. print("Height: "+str(vnT528d.height))  
  21. vnT528dCoordinate1=hvT528d.getAbsoluteCenterOfView(vnT528d)  
  22. print("vnT528dCoordinate1X: "+str(vnT528dCoordinate1.x))  
  23. print("vnT528dCoordinate1Y: "+str(vnT528dCoordinate1.y))  
  24. vnT528dCoordinate2=hvT528d.getAbsolutePositionOfView(vnT528d)  
  25. print("vnT528dCoordinate2X: "+str(vnT528dCoordinate2.x))  
  26. print("vnT528dCoordinate2Y: "+str(vnT528dCoordinate2.y))  

        附上运行结果:
Width: 165
Height: 49
vnT528dCoordinate1X: 127
vnT528dCoordinate1Y: 680
vnT528dCoordinate2X: 45
vnT528dCoordinate2Y: 656

        ViewNode类里面还有很多属性,包括parent(获取父控件)、children(获取子控件)、left、top等等,这里就不一个个挨着讲了,自己看吧,呵呵。


你可能感兴趣的:(MonkeyRunner)