Reputation: 364
I´m programming with Java in Android Studio.
I just don´t get it, why this happens:
The result of my setText()
method is always the same: "0" is shown as buttontext.
The setText
method of my button:
button_adj1.setText(String.valueOf(getResources().getIdentifier("adj"+ counter,"String", getPackageName())));
The counter variable works correctly and gets incremented after click, which should extract the counter+1
item at second click.
If I replace counter
with e.g. 3
, the result is also 0
.
Hardcoded attempt:
button_adj1.setText(String.valueOf(getResources().getIdentifier("adj"+ 3,"String", getPackageName())));
The resource file: res/strings.xml
:
<string name="adj1">Test0</string>
<string name="adj2"Test1</string>
<string name="adj3">Test2</string>
<string name="adj4">Test3</string>
<string name="adj5">Test4</string>
<string name="adj6">Test5</string>
<string name="adj7">Test6</string>
<string name="adj8">Test7</string>
<string name="adj9">Test8</string>
<string name="adj10">Test</string>
Is there any other possible way?
I thought String.valueOf
is converting the result of getResources.getIdentifier
into string?
Upvotes: 1
Views: 719
Reputation: 3234
Try changing it from:
button_adj1.setText(String.valueOf(getResources().getIdentifier("adj"+ counter,"String", getPackageName())));
To:
button_adj1.setText(getResources().getIdentifier("adj"+ counter,"string", getPackageName()));
The changes:
getIdentifier()
-> This solves the issue with the TextView
being set to 0
valueOf
and instead pass the resource ID of the string to setText()
-> This prevents the TextView
being set to 2131755036
for examplesetText()
has a couple of different overloads. But you want to ensure that this one is invoked:
public final void setText (int resid)
Not this one:
public final void setText (CharSequence text)
If on the other hand you want to use the latter overload, then getString()
must be called passing the integer value of the resource ID.
Upvotes: 1