SetText (getString (R.strings.whatever) or setText (R.strings.whatever)?

Both work, obviously, if you start concatenating, you will need to get a string to avoid displaying int.

Question: What is the most “elegant” or “recommended” to use?

thanks

+6
source share
3 answers

The second approach is more elegant, since inside the TextView (or any View class) it will perform the task of obtaining a string for the specified resource.

Providing components to internal work is always preferable. In addition, it is shorter and more readable.


About the internals that I talked about: if you look at the source code of Androids, you can see that the setText(int) method of TextView is executed as follows:

 public final void setText(int resid) { setText(getContext().getResources().getText(resid)); } 

So, it internally uses the Context class to get the string from the resource identifier. Now, if you look at the getText() method (which also comes from the Context class), you can see that it is implemented the same way :

 public final String getString(int resId) { return getResources().getString(resId); } 

Thus, for reasons of performance or reliability, this does not matter. However, it is shorter and more readable.

+8
source

Well, since the API provides a method for passing the identifier of a resource string, it seems logical to prefer to use this. You can really check the operation of setText (resourceid) to see under the hood, but setText (R.strings.whatever) is definitely recommended.

+1
source

You can add

 yourEditText.setText(getResources().getString(R.string.mytext)); 

because you need to get the context of the resource after receiving the string.

0
source

Source: https://habr.com/ru/post/913013/


All Articles