Get root view from current activity

后端 未结 12 1940
不知归路
不知归路 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 10:08

    anyview.getRootView(); will be the easiest way.

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

    Another Kotlin Extension solution

    If your activity's view is declared in xml (ex activity_root.xml), open the xml and assign an id to the root view:

    android:id="@+id/root_activity"
    

    Now in your class, import the view using:

    import kotlinx.android.synthetic.main.activity_root.root_activity
    

    You can now use root_activity as the view.

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

    Just incase Someone needs an easier way:

    The following code gives a view of the whole activity:

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

    To get a certian view in the activity,for example an imageView inside the activity, simply add the id of that view you want to get:

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

    Hope this helps somebody

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

    This is what I use to get the root view as found in the XML file assigned with setContentView:

    final ViewGroup viewGroup = (ViewGroup) ((ViewGroup) this
                .findViewById(android.R.id.content)).getChildAt(0);
    
    0 讨论(0)
  • 2020-11-22 10:20

    Get root view from current activity.

    Inside our activity we can get the root view with:

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

    or

    View rootView = getWindow().getDecorView().getRootView();
    
    0 讨论(0)
  • 2020-11-22 10:21

    If you need root view of your activity (so you can add your contents there) use

    findViewById(android.R.id.content).getRootView()
    

    Also it was reported that on some devices you have to use

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

    instead.

    Please note that as Booger reported, this may be behind navigation bar (with back button etc.) on some devices (but it seems on most devices it is not).

    If you need to get view that you added to your activity using setContentView() method then as pottedmeat wrote you can use

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

    But better just set id to this view in your xml layout and use this id instead.

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