Mar*_*cus 5 android view layout-inflater
我为活动创建了一个布局文件.在这个布局中,我创建了一个带有textview和edittext的LinearLayout.现在我想创建额外的LinearLayouts,它将查看并包含与原始LinearLayout完全相同的视图,但具有不同的文本.我还想在运行期间以编程方式执行此操作,因为这些LinearLayout的数量在运行之间会有所不同.我已经阅读了一些关于inflaters的内容,但我对它们的理解并不充分.
我在想这样的事情,显然代码是错误的,但希望你明白我想做什么:
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);
}
Run Code Online (Sandbox Code Playgroud)
jen*_*nzz 16
有几种方法可以实现这一目标.
一种快速简便的方法是在循环的每次迭代中扩展新布局:
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);
Run Code Online (Sandbox Code Playgroud)
另一个(更优雅的)解决方案是创建一个扩展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);
}
}
Run Code Online (Sandbox Code Playgroud)
现在,您可以ChildView
在循环的每个迭代中创建一个并通过以下setText(String text)
方法设置文本:
for (int i = 0; i < 10; i++) {
ChildView child = new ChildView( this );
child.setText("Child No. " + i);
parent.addView(child);
}
Run Code Online (Sandbox Code Playgroud)
您可以通过使用布局充气器来实现
使用这个来获取布局充气器
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);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
11739 次 |
最近记录: |