0

Why is this code wrong? It doesn't accept the setText function on a button.

findViewById(getResources().getIdentifier("button" + Integer.toString(i), "id", getPackageName()))
                .setText("abc");

But if I write like this

button1.setText("abc");

it is ok.

1
  • You can accept one answer (if it helps you) by click on big gray check button on its left side. If you wish you can add +10 points to any author of any good answer by click upper gray triangle Commented Dec 26, 2020 at 12:48

1 Answer 1

2

Because findViewById returns a view. View does not have a method called setText(). You should define that the view is a Button which does have a method called setText(). You can do that this way.

((Button)findViewById(getResources().getIdentifier("button" + Integer.toString(i), "id", getPackageName()))).setText("abc");

Sign up to request clarification or add additional context in comments.

2 Comments

It works, thank you. But I have a question: why I received a down vote?
I do not know but I assume that similar questions have been already asked. For example this kind of answers your question. If this answers your question, you can accept it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.