android开发分享从当前活动获取根视图

我知道如何使用View.getRootView()获得根视图。 我也可以从一个button的onClick事件的参数是一个视图 。 但是我怎样才能看到一个活动的观点

    如果你需要你的活动的根视图(所以你可以添加你的内容)使用

     findViewById(android.R.id.content) 

    另据报道,在一些设备上,你必须使用

     getWindow().getDecorView().findViewById(android.R.id.content) 

    代替。

    请注意,正如Booger所报道的,在某些设备上,这可能位于导航栏(带有后退button等)的后面(但在大多数设备上似乎不是这样)。

    如果您需要查看您使用setContentView()方法添加到您的活动,然后pottedmeat写你可以使用

     final ViewGroup viewGroup = (ViewGroup) ((ViewGroup) this .findViewById(android.R.id.content)).getChildAt(0); 

    但更好的只是在你的XML布局中设置ID到这个视图,而不是使用这个ID。

    这是我用来获得在分配给setContentView的XML文件中find的根视图:

     final ViewGroup viewGroup = (ViewGroup) ((ViewGroup) this .findViewById(android.R.id.content)).getChildAt(0); 

    我只在android 4.0.3中testing过这个:

     getWindow().getDecorView().getRootView() 

    给我们从我们得到的相同的看法

     anyview.getRootView(); com.android.internal.policy.impl.PhoneWindow$DecorView@######### 

     getWindow().getDecorView().findViewById(android.R.id.content) 

    给孩子的

     android.widget.FrameLayout@####### 

    请确认。

    只要incase有人需要一个更简单的方法:

    以下代码给出了整个活动的视图:

    View v1 = getWindow().getDecorView().getRootView();

    要在活动中获得一个certian视图,例如在活动中的一个imageView,只需添加你想获得的视图的id:

     View v1 = getWindow().getDecorView().getRootView().findViewById(R.id.imageView1); 

    希望这有助于某人

    在我们的活动内部,我们可以通过

     ViewGroup rootView = (ViewGroup) ((ViewGroup) this .findViewById(android.R.id.content)).getChildAt(0); 

    要么

     View rootView = getWindow().getDecorView().getRootView(); 

    如果你在一个活动中,假设只有一个根视图,你可以像这样得到它。

     ViewGroup viewGroup = (ViewGroup) ((ViewGroup) this .findViewById(android.R.id.content)).getChildAt(0); 

    然后你可以把它投到你的真实课堂上

    或者你可以使用

     getWindow().getDecorView(); 

    注意这将包括操作栏视图,您的视图在操作栏视图下方

      以上就是android开发分享从当前活动获取根视图相关内容,想了解更多android开发(异常处理)及android游戏开发关注(计算机技术网)。

      本文来自网络收集,不代表计算机技术网立场,如涉及侵权请点击右边联系管理员删除。

      如若转载,请注明出处:https://www.ctvol.com/addevelopment/524041.html

      (0)
      上一篇 2020年12月13日
      下一篇 2020年12月13日

      精彩推荐