What is this R.id.home?

Viewed 2326

Multiple parent Activities for one child activity toolbar Back Button

@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
    int id = item.getItemId();
    if (id == android.R.id.home) {
        onBackPressed();
        return true;
    }
    return super.onOptionsItemSelected(item);
}

I have to Override this function for the functionality of the back button, call back to the same parent activity from which the child is called but I don't understand this code of line:
id == android.R.id.home
What is the R.id.home? home represent for? is I have to use the same R.id.home Everywhere, where ever I have to use this back button functionality in my app?

3 Answers

You're probably used to using R.id.whatever to refer to the IDs you've given to the views in your app. Giving a TextView an ID of label, and then you can find it by looking for the view with R.id.label for its ID, that kind of thing.

That R file is generated for your app, based on the resources you've added or declared. But android.R.id.home is an ID in Android's R file - you can think of it like a separate set of system resources. It won't conflict with anything you've given a "home" ID to, because that would be R.id.home instead.

When you call setHomeButtonEnabled on your toolbar, Android adds its own icon, and it gives that an internal ID of android.R.id.home. That's always the identifier for that home button, and you can check if it's been pressed by checking for that ID when a menu item is selected.

R is the way to get things from the Android resources pack. id is telling it that you want an id from it (you can also ask it for other things, like strings).

home is the actual ID that you are asking it for. It is probably a button judging by your question. IDs are set in the view editor.

Editor window

If you have a search around your application, you will probably find a button with the ID home.

A very short answer is: a way of accessing resources.
Resources could be TextView, Button and also some Strings, Drawable images as well.

R.id.home represents some particular resource which is MentuItem, so this way the code determines if the MenuItem is selected or not - there could be several MenuItem in the Menu so, the code finds out if the MenuItem with id=home selected or not.

You should have something like this in your Menu HTML file:

<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
    android:id="@+id/home"        
    android:title="BlaBlaBla"
/>
...

Important note: every resources must have different identifiers (id) to avoid ambiguous accessing.

Here you can find detailed information about R with explained use cases. Here

Related