0

I was wondering if there is a way to dynamically create an additional linear layout with a textview within a predefined liner layout. THis is my code so you get the gist of what I am asking:

LinearLayout MainLL= (LinearLayout) findViewById(R.id.myLayoutId); 

  for(int i=0; i<5; i++)
  {
   LinearLayout childLL= new LinearLayout(this);
   childLL.setOrientation(LinearLayout.VERTICAL);  
   childLL.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));  
   childLL.setGravity(Gravity.LEFT);

 TextView text = new TextView(this);
   text.setText("The Value of i is :"i);
   text.setTextSize(12);  
   text.setGravity(Gravity.LEFT);
   text.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
childLL.addView(text);
MainLL.addView(childLL);
}

My problem is that I am only getting "The Value of i is :0" as the output, i.e. the first instance.

Any help would be much appreciated

3 Answers 3

4

You don't need to wrap the TextView inside another LinearLayout, you can do just:

LinearLayout MainLL= (LinearLayout) findViewById(R.id.myLayoutId); 
  for(int i=0; i<5; i++){
 TextView text = new TextView(this);
   text.setText("The Value of i is :"+i); // <-- does it really compile without the + sign?
   text.setTextSize(12);  
   text.setGravity(Gravity.LEFT);
   text.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
MainLL.addView(text);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks all, you have pointed me in the right direction but I figured out my flaw. I forgot to have a setContent view. Adding the following to the end solved the problem: this.setContentView(MainLL);
0

Everything you are doing is correct just make it

childLL.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));  

because your parent layout is filled by 1st view because of that you can not see other view.

and yes

 text.setText("The Value of i is :"+i); //add + sign

Comments

0

Yes, if you greatly need to wrap another LinearLayout before wrapping the TextView. Please try this code:

childLL.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1f));  

This will ensure the wrapped LinearLayout has the same weight, so all the views will be displayed on the screen.

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.