Duplicate views in Android at runtime

I created a layout file for the action. In this layout, I created a LinearLayout with text and edittext. Now I want to create additional LinearLayouts that will look and contain the same looks as my original LinearLayout, but with different texts. I also want to do this programmatically during the run, because the number of these LinearLayout will vary depending on the run. I read some about inflatable devices, but I do not understand them enough to use them.

I think about it, obviously the code is wrong, but hopefully you understand what I want to do:

LinearLayout llMain = (LinearLayout)findViewById(R.id.mainLayout);
LinearLayout llToCopy = (LinearLayout)findViewById(R.id.linearLayoutToCopy);
for(int player = 0; player < size; player++)
{
   LinearLayout llCopy = llToCopy.clone();
   TextView tv = (TextView)llCopy.getChildAt(0);
   tv.setText(players.get(player).getName());
   llMain.addView(llCopy);
}
+5
source share
2 answers

.
- :

LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout parent = (LinearLayout) inflater.inflate(R.layout.main, null);

for (int i = 0; i < 10; i++) {
    View child = inflater.inflate(R.layout.child, null);
    TextView tv = (TextView) child.findViewById(R.id.text);
    tv.setText("Child No. " + i);
    parent.addView(child);
}

setContentView(parent);

( ) , LinearLayout:

public class ChildView extends LinearLayout {

    private TextView tv;

    public ChildView(Context context) {
        super(context);

        View.inflate(context, R.layout.child, this);
        tv = (TextView) findViewById(R.id.text);
    }

    public void setText(String text) {
        tv.setText(text);
    }
}

ChildView setText(String text):

for (int i = 0; i < 10; i++) {
    ChildView child = new ChildView( this );
    child.setText("Child No. " + i);
    parent.addView(child);
}
+16

,

,

LayoutInflater inflater = (LayoutInflater) context.getSystemService
      (Context.LAYOUT_INFLATER_SERVICE);
LinearLayout newlayout = inflater.inflate(R.layout.yourlayout, null);

// newlayout is the copy of your layout and you can use it and to get 
// the textview and edittext do it like this

TextView text = (TextView) newlayout.findView(R.id.yourtextviewid);
text.setText("new text");
EditText et = (EditText) newlayout.findView(R.id.yourtextviewid);
+4

All Articles