Get root view from current activity

后端 未结 12 1939
不知归路
不知归路 2020-11-22 09:18

I know how to get the root view with View.getRootView(). I am also able to get the view from a button\'s onClick event where the argument is a View. But how can

相关标签:
12条回答
  • 2020-11-22 09:57

    I tested this in android 4.0.3, only:

    getWindow().getDecorView().getRootView()
    

    give the same view what we get from

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

    and

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

    giving child of its

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

    Please confirm.

    0 讨论(0)
  • 2020-11-22 09:57

    Kotlin Extension Solution

    Use this to simplify access in an Activity. Then you can directly refer to rootView from the Activity, or activity.rootView outside of it:

    val Activity.rootView get() = window.decorView.rootView
    

    If you'd like to add the same for Fragments for consistency, add:

    val Fragment.rootView get() = view?.rootView
    
    0 讨论(0)
  • 2020-11-22 10:02

    For those of you who are using the Data Binding Library, to get the root of the current activity, simply use:

    View rootView = dataBinding.getRoot();
    

    And for Kotlin users, it's even simpler:

    val rootView = dataBinding.root
    
    0 讨论(0)
  • 2020-11-22 10:03

    if you are in a activity, assume there is only one root view,you can get it like this.

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

    you can then cast it to your real class

    or you could using

    getWindow().getDecorView();
    

    notice this will include the actionbar view, your view is below the actionbar view

    0 讨论(0)
  • 2020-11-22 10:05

    In Kotlin we can do it a little shorter:

    val rootView = window.decorView.rootView
    
    0 讨论(0)
  • 2020-11-22 10:05

    to get View of the current Activity

    in any onClick we will be getting "View view", by using 'view' get the rootView.

    View view = view.getRootView();

    and to get View in fragment

    View view = FragmentClass.getView();

    0 讨论(0)
提交回复
热议问题