我想以编程方式创建一个布局表单。例如,我想在我的表单中添加类似textview的视图几次。我创建了另一个具有textview的布局,现在我想在我当前的布局中添加这个textview几次。
public class FileForm extends Activity {
LinearLayout LIN_Main;
TextView TV_GroupTitle;
LayoutInflater LYOTInf;
View VIW_AllItems;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_file_form);
LIN_Main = (LinearLayout) findViewById(R.id.LIN_Main);
LYOTInf = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
VIW_AllItems = LYOTInf.inflate(R.layout.item,null);
TV_GroupTitle = (TextView) VIW_AllItems.findViewById(R.id.TV_GroupTitle);
int INT_GroupNum = 0;
List<Integer> INT_EmNumInGroup = new ArrayList<Integer>();;
EmManager EMM = null;
EMM = EMM.getInstance();
Element EmNode = EMM.getEm();
Element EmG = null;
Element EmE = null;
NodeList Group = null;
NodeList EmList = null;
Group = EmNode.getChildNodes();
INT_GroupNum = Group.getLength();
LIN_Main.removeAllViews();
for (int i=0;i<INT_GroupNum;i++)
{
EmList = Group.item(i).getChildNodes();
INT_EmNumInGroup.add(EmList.getLength());
for (int j=0;j<INT_EmNumInGroup.get(i);j++)
{
EmE = (Element) EmList.item(j);
for(int att=0;att<Integer.parseInt(EmE.getAttribute("Num"));att++)
{
TV_GroupTitle.setText(EmE.getNodeName());
LIN_Main.addView(TV_GroupTitle);
}
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.file_form, menu);
return true;
}
}
但是有错误。
答案 0 :(得分:1)
您必须以编程方式创建TextView(TextView text = new TextView(context)),而不是findviewById,您必须在for中执行此操作,如下所示:
for (int j=0;j<INT_EmNumInGroup.get(i);j++)
{
EmE = (Element) EmList.item(j);
for(int att=0;att<Integer.parseInt(EmE.getAttribute("Num"));att++)
{
TextView TV_GroupTitle = new TextView(this)
TV_GroupTitle.setText(EmE.getNodeName());
LIN_Main.addView(TV_GroupTitle);
}
}
答案 1 :(得分:1)
您可以根据需要随时充气布局
for(int att=0;att<Integer.parseInt(EmE.getAttribute("Num"));att++) {
TextView textView = (TextView)LYOTInf.inflate(R.layout.item,null);
LIN_Main.addView(textView);
}
或者只是以编程方式创建新的TextView对象
for(int att=0;att<Integer.parseInt(EmE.getAttribute("Num"));att++) {
TextView textView = new TextView(context);
//Configure the textView here (LayoutParams, ...)
LIN_Main.addView(textView);
}
确保每行都有一个新对象!您不能只在同一个对象上设置文本并再次添加(就像您一样)
for(int att=0;att<Integer.parseInt(EmE.getAttribute("Num"));att++)
{
TV_GroupTitle.setText(EmE.getNodeName());
LIN_Main.addView(TV_GroupTitle);
}