0

I want to add a LinearLayout wrapped around a TextView and Button programmatically. I want it to take a String array and then using the length of the string array, add that many TextViews each with their own button.

So first:

String [] s = { .... the values ....}
int sL = s.length;
TextView t1 = new TextView (this);
// then somehow create t2, t3... etc. matching the length of the String array.

Is this the best way to do this or is there another way to do this? For some context, it's a quiz app and I've created a list of categories inside resources as values and I'm trying to programmatically get my app to create as many TextViews as there are categories then set each TextView to each category then get each button to take the user to that category of questions.

2 Answers 2

2

You are starting it right, just do a for loop and add textviews to your linearlayout.

// You linearlayout in which you want your textview
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.mylayout);
linearLayout.setBackgroundColor(Color.TRANSPARENT);

String [] s = { .... the values ....}
int sL = s.length;
TextView textView = null;

// For later use if you'd like
ArrayList<TextView> tViews = new ArrayList<TextView>();

for (int i = 0; i < sL; i++)
{
    textView = new TextView(this);
    textView.setText(s[i]);
    linearLayout.addView(textView);
    tViews.add(textView);
}

There is nothing wrong with this way of doing it. If you want to use these textview later on (set text for them or something) store them in an Array of some kind. Edited code

Sign up to request clarification or add additional context in comments.

6 Comments

But he has no reference to those TextViews, best to put them in a List or Array first.
Why does he needs references? =/
Because.. he would want to do something with the TextViews later on maybe?
Well yeah but that wasn't the question though :) edited answer
Thank you very much :D That looks awesome! And just finishing it off if I want to set the text of textview 1 to s[1], TextView 2 to s[2] etc do I just use this: textView.setText(s[i]); after textView = new TextView(this);?
|
0

You can do the following:

for(int i=0;i<s.length;i++){
  TextView t=new TextView(this);
  t.setText(s[i]);
  yourLinearLayout.addView(t);
}

But I really think that using a ListView would be better for performance ;)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.