Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get current content view in Android programming?

Tags:

java

android

I know that I can set the content of the view in an Android app by saying setContentView(int). Is there a function I can use to know what the current content view is? I don't know if that makes any sense, but what I'm looking for is a function called, say, getContentView that returns an int.

Ideally, it would look like this:

setContentView(R.layout.main); // sets the content view to main.xml
int contentView = getContentView(); // does this function exist?

How would I do that?

like image 298
Lincoln Bergeson Avatar asked Nov 16 '12 00:11

Lincoln Bergeson


2 Answers

Citing Any easy, generic way in Android to get the root View of a layout?

This answer and comments give one method: [Get root view from current activity

findViewById(android.R.id.content)

Given any view in your hierarchy you can also call:

view.getRootView()

to obtain the root view of that hierarchy.

The "decor view" can also be obtained via getWindow().getDecorView(). This is the root of the view hierarchy and the point where it attaches to the window, but I'm not sure you want to be messing with it directly.

like image 139
Robert Estivill Avatar answered Sep 20 '22 01:09

Robert Estivill


In an Activity, you can do

View rootView = null;
View currentFocus = getWindow().getCurrentFocus();
if (currentFocus != null)
    rootView = currentFocus.getRootView();

As described above, there is also

View decorView = getWindow().getDecorView();

as well as

View decorView = getWindow().peekDecorView();

The difference between the latter two is that peekDecorView() may return null if the decor view has not been created yet, whereas getDecorView() will create a new decor view if none exists (yet). The first example may also return null if no view currently has focus.

I haven't tried out whether the root view and the decor view are the same instance. Based on the documentation, though, I would assume they are, and it could be easily verified with a few lines of code.

like image 34
user149408 Avatar answered Sep 21 '22 01:09

user149408