How to programmatically get resource Id for android.R.id.content?

CaptAmericode picture CaptAmericode · Feb 18, 2014 · Viewed 7.6k times · Source

I'm trying to do this in a library project...

int containerViewId = getResources().getIdentifier("content", "android.R.id", getPackageName());

getFragmentManager().beginTransaction().replace(containerViewId, new SettingsFragment()).commit();

But I get this exception on the replace: Caused by: java.lang.IllegalArgumentException: Must use non-zero containerViewId

How do I get resource id for android.R.id.content programmatically?

Thanks.

Edit: I have solved it by using a named view, setting the id in the xml layout of the activity and using the following code to replace the root view...

int containerViewId = getResources().getIdentifier("rootView", "id", getPackageName());
getFragmentManager().beginTransaction().replace(containerViewId, new SettingsFragment()).commit();

Answer

David C Adams picture David C Adams · Feb 18, 2014
int containerViewId = findViewById(android.R.id.content) 

should work. You have to make sure you are using the Activity's context though. You can also use Activity.getWindow().getDecorView() to get the top view.