Get root view from current activity

2018-12-31 16:01发布

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 I get the view in an activity?

9条回答
君临天下
2楼-- · 2018-12-31 16:31

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();

查看更多
孤独总比滥情好
3楼-- · 2018-12-31 16:35

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

查看更多
大哥的爱人
4楼-- · 2018-12-31 16:41

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

查看更多
有味是清欢
5楼-- · 2018-12-31 16:46

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

findViewById(android.R.id.content)

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.

查看更多
只若初见
6楼-- · 2018-12-31 16:47

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);
查看更多
皆成旧梦
7楼-- · 2018-12-31 16:51

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.

查看更多
登录 后发表回答