K. Barresi K. Barresi - 15 days ago 5
Android Question

Android: Adding Layouts Dynamically By Inflating XML

I'm trying to have a function where a layout is added to my view when a button is pressed. The ID's of 2

EditText
s in the layout are added to a
List<EditText>
, so I can access them no matter how many instances of the XML layout are added. However, I'm having troubles getting this to work.

Main function setting up the view:

ViewGroup view = null;
TextView addressView;
Button submit;
ImageView addHeader;

private int id = 0;
private List<EditText> editTexts = new ArrayList<EditText>();


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.get);

view = (ViewGroup) findViewById(R.id.getLayout);


addressView = (TextView) view.findViewById(R.id.getAddress);
submit = (Button) view.findViewById(R.id.getSubmit);
addHeader = (ImageView) view.findViewById(R.id.getHeaderAdd);

addHeader.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
addHeaderBox();
}
});


My function adding the layout:

private void addHeaderBox() {
LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

inflater.inflate(R.layout.get_param, view, false);

EditText nameBox = (EditText) view.findViewById(R.id.getValue);
EditText valueBox = (EditText) view.findViewById(R.id.getName);

nameBox.setId(id++);
valueBox.setId(id++);

editTexts.add(nameBox);
editTexts.add(valueBox);
}


getValue
and
getName
are the ID's of the two
EditText
s in my layout (not the main
getLayout
).

07-19 10:25:13.088: E/AndroidRuntime(32034): java.lang.NullPointerException
07-19 10:25:13.088: E/AndroidRuntime(32034): at myapp.httprequest.free.GETActivity.addHeaderBox(GETActivity.java:96)
07-19 10:25:13.088: E/AndroidRuntime(32034): at myapp.httprequest.free.GETActivity.access$0(GETActivity.java:88)
07-19 10:25:13.088: E/AndroidRuntime(32034): at myapp.httprequest.free.GETActivity$1.onClick(GETActivity.java:65)


Line 96 is
nameBox.setId(id++)

Answer

Try:

.......
View someView = inflater.inflate(R.layout.get_param, view, false);

EditText nameBox = (EditText) someView.findViewById(R.id.getValue);
EditText valueBox = (EditText) someView.findViewById(R.id.getName);
........ 
Comments