Answer the question
In order to leave comments, you need to log in
Android How to display different layout.xml in one ListView in a loop?
There is a ListView on the Activity, there is an array of data (contact sheet) that needs to be displayed in the ListView. How to display array elements differently?
contacts is a json string
contactsList = new ArrayList<HashMap<String, String>>();
lv_contacts = (ListView) findViewById(R.id.lv_contacts);
try {//Считаем контакты и заносим в contactsList
mArray = new JSONArray(contacts);
for (int i = 0; i < mArray.length(); i++) {
JSONObject mJsonObject = mArray.getJSONObject(i);
HashMap<String, String> map = new HashMap<String, String>();
map.put("cid", mJsonObject.getString("cid"));
map.put("name", mJsonObject.getString("name"));
contactsList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
ListAdapter adapter = new SimpleAdapter(
ContactsActivity.this, contactsList, R.layout.item_contactslist,
new String[] { "cid","name"}, new int[] { R.id.cid, R.id.name });
lv_contacts.setAdapter(adapter);
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/list_item"
android:gravity="center_vertical">
<TextView
android:id="@+id/cid"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:visibility="gone" />
<TextView
android:id="@+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingTop="6dp"
android:paddingLeft="6dp"
android:textSize="17sp"
android:textStyle="bold" />
</LinearLayout>
Answer the question
In order to leave comments, you need to log in
Make several layouts with the necessary styles for the list element. Write your adapter for the list. In the method that gives the layout for the element, specify which one to give depending on the evenness of the element number, if it is necessary that there be alternation, for example.
You need a custom adapter. Something like:
private class MySimpleAdapter extends SimpleAdapter{
public MySimpleAdapter(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to) {
super(context, data, resource, from, to);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout. item_contactslist, null);
}
HashMap<String, String> item = (HashMap<String, String>) ListOfContacts.getItemAtPosition(position);
if(item.get("name") != null){
name.setText(item.get("name"));
}else{
name.setText("NoNamed");
}
return v;
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question