Search code examples
javaandroidtextviewfindviewbyid

FindViewById Multiple Times on a Single Line


This is not a problem, but more of an efficiency question. I have multiple TextViews (2 of them) in my XML Layout of my Android App. My question is that can I select multiple TextViews, findViewById multiple TextViews on a single line?

Is this valid for my question?

TextView title, darkThemeTitle = findViewById(R.id.title); findViewById(R.id.darkThemeTitle);

Solution

  • When you use TextView title, darkThemeTitle = findViewById(R.id.title); findViewById(R.id.darkThemeTitle); in your code .

    • This line TextView title, darkThemeTitle = (TextView) findViewById(R.id.title); will show that Variable 'title' might not have been initialized .So title never initialized in the code .

    • And findViewById(R.id.tab_layout); will return View in your code .And it never return darkThemeTitle in your code .

    And you can do like this .

     TextView title = (TextView) findViewById(R.id.title); TextView darkThemeTitle = (TextView) findViewById(R.id.darkThemeTitle);
    

    Another way

    TextView title = null, darkThemeTitle = null;
    
    TextView[] textViews = {title, darkThemeTitle};
    Integer[] ids = {R.id.title, R.id.darkThemeTitle};
    
    for (int i = 0; i < textViews.length; i++) {
        textViews[i] = (TextView) findViewById(ids[i]);
    }