How can I display an Integer value in TextView?
When I try, I get an error a开发者_如何学Pythonndroid.content.res.Resources$NotFoundException: String resource ID
TextView tv = new TextView(this);
tv.setText(String.valueOf(number));
or
tv.setText(""+number);
TextView tv = new TextView(this);
tv.setText("" + 4);
If you want it to display on your layout you should
For example:
activity_layout.XML file
<TextView
android:id="@+id/example_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
On the activity.java file
final TextView textView = findViewById(R.id.example_tv);
textView.setText(Integer.toString(yourNumberHere));
In the first line on the XML file you can see:
android:id="@+id/example_tv"
That's where you get the id to change in the .java file for the findViewById(R.id.example_tv)
Hope I made myself clear, I just went with this explanation because a lot of times people seem to know the ".setText()" method, they just can't change the text in the "UI".
EDIT Since this is a fairly old answer, and Kotlin is the preferred language for Android development, here's its counterpart.
With the same XML layout:
You can either use the findViewbyId()
or use Kotlin synthetic properties:
findViewById<TextView>(R.id.example_tv).text = yourNumberHere.toString()
// Or
example_tv?.text = yourNumberHere.toString()
The toString()
is from Kotlin's Any
object (comparable to the Java Object
):
The root of the Kotlin class hierarchy. Every Kotlin class has Any as a superclass.
Consider using String#format with proper format specifications (%d or %f) instead.
int value = 10;
textView.setText(String.format("%d",value));
This will handle fraction separator and locale specific digits properly
Alternative approach:
TextView tv = new TextView(this);
tv.setText(Integer.toString(integer));
String s = Integer.toString(10);
Then setText(s)
just found an advance and most currently used method to set string in textView
textView.setText(String.valueOf(YourIntegerNumber));
It might be cleaner for some people to work with an Integer object so you can just call toString() directly on the object:
Integer length = my_text_view.getText().getLength();
counter_text_view.setText( length.toString() );
tv.setText(Integer.toString(intValue))
精彩评论