Reputation: 21
I'm trying to port a project I did in JavaScript to Java (Android), and I'm having trouble figuring out how to do certain things in Java and Android Studio that were different in JS. Right now I'm trying to figure out how to do this fix I had in the original JS program that took advantage of the naming convention I used to let me loop through each text label.
for(var i = 0; i <= 5; i++)
{
for(var j = 0; j <= 5; j++)
{
setText("lbl" + i + j, text);
}
}
If I had label00 - label12, this could loop through all of them and set text accordingly, but I don't know how to adapt this to the setText method in Android Studio.I wanted to try something like this, but it's saying "Identifier Expected" where the findViewById command has quotes after the second period.
TextView lblID = (TextView) findViewById(R.id."lbl" + i + j);
lblID.setTextColor(Color.parseColor("#186cb3"));
Most of the UI control was based on this principal, so I need something similar if I can't get this working.
Upvotes: 0
Views: 47
Reputation: 69
This is definitely not the right way for you to port from JavaScript to Android (with Java). The findViewById()
method is used to find a certain view on the root layout of your screen using a specified id
, it is not for setting text. You need to create a new TextView
dynamically:
TextView textView = new TextView();
textView.setText("lbl" + i + j);
setTextColor(parseColor("#186cb3"));
then add the textView to the parent view of your layout:
parentView.addView(textView);
The parentView
is usually the viewGroup
on your activity layout file eg. RelativeLayout
, LinearLayout
. You need to give it an id
and get an instance of it like this:
RelativeLayout parentView = (RelativeLayout)
findViewById(R.id.parent_view_id);
Upvotes: 2