Android: How to look up a widget (defined in XML layout file) by its id

Android FAQ: How do I look up (find) a widget in my Java code that I’ve defined in an XML layout file?

Solution: When you define your Android widgets in XML and then need to find a widget by its id, the method you need is named findViewById., and it’s in the View object of your layout.

For example, you’ll use code like this to look up a TextView widget by its id, and create an instance of it in your Java code:

TextView quoteLabel = (TextView)rootView.findViewById(R.id.put_quote_here);

You’ll use code like that in an Activity or Fragment, and the rootView shown in this example is a View. (More on this in a few moments.)

But first ... to set the text on that TextView widget, use the setText method:

quoteLabel.setText(quote);

Full findViewById source code

For this example it may help to see all of the source code for the method:

@Override
public View onCreateView(LayoutInflater inflater,
                         ViewGroup container,
                         Bundle savedInstanceState) {

    // this first line gets an 'extra' from the activity's intent (not important for this example)
    String quote = (String)getActivity().getIntent().getStringExtra(PollingService.INTENT_KEY);

    // the layout file is named 'res/layout/fragment_show_full_quote.xml'
    View rootView = inflater.inflate(R.layout.fragment_show_full_quote, container, false);
    TextView quoteLabel = (TextView)rootView.findViewById(R.id.put_quote_here);

    // change the text on the TextView
    quoteLabel.setText(quote);
    return rootView;
}

Again, the purpose of this tutorial is to show how to look up an Android widget in its XML layout file and create it in Java code, and for the purpose you only need to see these two lines of code:

View rootView = inflater.inflate(R.layout.fragment_show_full_quote, container, false);
TextView quoteLabel = (TextView)rootView.findViewById(R.id.put_quote_here);

Once you write a lot of Android code you’ll remember this ... for now, just remember to get your hands on the View the widget is defined in, then use your IDE and search for a method beginning with find ... after a while that becomes a simple habit.