Search code examples
androidcastingfindviewbyid

findViewById doesn't seem to return correct view type?


Since we don't have to cast anymore, I expected findViewById to return the correct type, but it doesn't seem to do that. I'm obviously making a very simple mistake here, can you point it out?

I have a TextView's ID (since I created it dynamically) and want to change the text size of that item, this snippet works fine:

        TextView tmpView = findViewById(chain.getIngredientNameId());
        tmpView.setTextSize(8);

But this one doesn't:

        findViewById(chain.getIngredientNameId()).setTextSize(8);

So I assume I have to case it to TextView but none of my attempts seems to work (using () or <>), what obvious thing am I missing?


Solution

  • You should cast it if do not save to variable.

    TextView tmpView = findViewById(chain.getIngredientNameId());          //TextVeiw
    ((TextView) findViewById(chain.getIngredientNameId())).setTextSize(8); // TextVeiw
    findViewById(chain.getIngredientNameId());                             // View