Ashkan Mobayen Khiabani Ashkan Mobayen Khiabani - 3 months ago 24
Java Question

getLayoutInflater().inflate() in a loop always returns the first view

The

tics
have 3 items. the following code creates the 3 ticket items but always sets the text of the
TextView
s of the first ticket.

public void onSuccess(int i, Header[] headers, byte[] bytes) {
progress.dismiss();
String response = new String(bytes);
try{
JSONObject obj = new JSONObject(response);
JSONArray tics = obj.getJSONArray("tickets");
LinearLayout p = (LinearLayout)findViewById(R.id.tickets);

for(int j = 0;j<tics.length();j++){
LinearLayout t =(LinearLayout) getLayoutInflater().inflate(R.layout.ticket_row, p);
TextView topic = (TextView)t.findViewWithTag("topic");
TextView section = (TextView)t.findViewWithTag("section");
TextView datetime = (TextView)t.findViewWithTag("datetime");
JSONObject item = tics.getJSONObject(j);
Toast.makeText(getApplicationContext(),item.getString("Caption") ,Toast.LENGTH_LONG).show();
topic.setText(item.getString("Caption"));
datetime.setText(item.getString("DateString"));
section.setText(item.getString("Section"));
}
}catch (Exception e){}
}


In the following code:

LinearLayout t =(LinearLayout) getLayoutInflater().inflate(R.layout.ticket_row, p);


Shouldn't
t
be the inflated
View
?

Answer

Shouldn't t be the inflated View?

No, the version you are using adds the inflated view to the parent and returns the parent itself. You could use

View inflate (XmlPullParser parser, 
                ViewGroup root, 
                boolean attachToRoot)

providing false as third parameter. This way android will return the inflated view (the parent will be used only for the sake of the layout parmas). You will have to add it to the parent manually tho.