Farhad Aghajanian Farhad Aghajanian - 22 days ago 7
Android Question

how can i add a view like textview from another layout to current layout in android

I want to create a layout form Programmatically . for this for example i want to add a view like textview in my form a couple of times . i created another layout that has a textview now i want to add this textview a couple of times in my current layout .

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

}


but there is error .

Answer

you must to create the TextView programmatically (TextView text = new TextView(context)), not with the findviewById and you must do it in the for, like this:

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

                }

            }