PowenKo, android, Tutorial 020-7, Layout, add other layout via code at the run-time


sample 1:

add TextView at the run time.

ArrayList<String> myList = getData();
    for(String data : myList) {

        LinearLayout layout = new LinearLayout(this);
        layout.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,             LayoutParams.WRAP_CONTENT));
        TextView textView = new TextView(this);
        textView.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));

        textView.setText("hi!");

        layout.addChild(textView);         

        parentPanel.addView(layout);
    }

sample 2, add and remove the view at the run-time:

For ur requirement , u can use a single linear layout and add child views to it whenever u need a new View.

for example ,

LinearLayout parent = new LinearLayout ( context );
 
parent.setLayoutParams(width, height ); 
//width, height can be set as needed.
 
parent.addView(myView , 0 );

When u have formed a new LinearLayout as the next View , it can be added as the child to the parent .

Now,

parent.addView(newLinearLayout, 0 );

You can remove the previous View that u had added to the parent first by calling

parent.removeViewAt(1);

because after the new child was added , the previous view would have now become the second (index = 1 ) child.

You can apply the above logic whenever u have to display a new View.


Leave a Reply