Issue
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?
Solution
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:
- Use "string" not "String" in the call to
getIdentifier()
-> This solves the issue with theTextView
being set to0
- Remove
valueOf
and instead pass the resource ID of the string tosetText()
-> This prevents theTextView
being set to2131755036
for example
setText()
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.
Answered By - Elletlar
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.