Duplicate Views on Android during Run-time

2019-02-10 08:56发布

I have created a Layout file for an activity. In this layout I have created a LinearLayout with a textview and an edittext. Now I want to create additional LinearLayouts that will look and contain the exact same views that my original LinearLayout, but with different texts. I also want to do it programmatically during run because the amount of these LinearLayout will vary between runs. I've read some about inflaters but I don't understand them enough to use them.

I'm thinking something like this, 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);
}

2条回答
SAY GOODBYE
2楼-- · 2019-02-10 09:31

You can achieve that by using layout inflater

get the layout inflatter by using this

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);
查看更多
迷人小祖宗
3楼-- · 2019-02-10 09:32

There are several ways to accomplish this.
A quick and easy approach is to inflate a new layout in every iteration of the loop:

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);

Another (more elegant) solution is to create a separate class extending 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);
    }
}

Now you can create a ChildView in every iteration of your loop and set the text via the setText(String text) method:

for (int i = 0; i < 10; i++) {
    ChildView child = new ChildView( this );
    child.setText("Child No. " + i);
    parent.addView(child);
}
查看更多
登录 后发表回答