Reputation: 5697
I'm trying to simplify my code, but for some reasons the "setText" method is not available.
Here is the code which is currently working for me:
TextView textView = (TextView)view.findViewById(R.id.testId);
textView.setText("Test");
I'm trying to simply it to this code:
(TextView)view.findViewById(R.id.testId).setText("Test");
But I'm getting the error message: "Cannot find symbol". Even IDE does not give me this option:
However, this code is working fine for some other things, like this:
view.findViewById(R.id.another_testID).setOnClickListener(test_listener);
Any ideas?
Upvotes: 0
Views: 135
Reputation: 28579
As you currently have (TextView)view.findViewById(R.id.testId).setText("Test");
, findViewById returns a standard View
, wehre as the setText method is a property of a TextView
.
In this statement, you are attempting to cast view.findViewById(R.id.testId).setText("Test")
to a TextView.
The 2
line solution you have above is the simplest way to set the text.
EDIT
To do this in a single line:
((TextView)findViewById(R.id.testId)).setText("Test");
In this line, you are setting the property of the TypeCast element. In your example, you had the property settings as a part of the typecast.
If you ever in the same class need to change the text of this element, this is not the best method as it will eat up extra clock cycles as opposed to just keeping a variable of the element.
Upvotes: 3
Reputation: 36449
For a one liner:
((TextView)view.findViewById(R.id.testId)).setText("Test");
Note the extra brackets added.
Upvotes: 6