您需要創建自己的適配器類:
public class MyAdapter extends ArrayAdapter<User> {
public MyAdapter(Context context, ArrayList<User> users) {
super(context, 0, users);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
User user = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_user, parent, false);
}
// Lookup view for data population
TextView tvName = (TextView) convertView.findViewById(R.id.tvName);
ImageView ivPhoto = (ImageView) convertView.findViewById(R.id.ivPhoto);
// Populate the data into the template view using the data object
tvName.setText(user.name);
ivPhoto.setImageResource(user.photo);
// Return the completed view to render on screen
return convertView;
}
}
然後XML爲您排:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:id="@+id/ivPhoto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@android:drawable/sym_def_app_icon" />
<TextView
android:id="@+id/tvName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name" />
然後您的自定義,例如用戶等級:
public class User {
public String name;
public int photo;
public User(String name, int photo) {
this.name = name;
this.photo = photo;
}
}
在你的主要clas把這個:
// Construct the data source
ArrayList<User> arrayOfUsers = new ArrayList<User>();
// Create the adapter to convert the array to views
MyAdapter adapter = new MyAdapter(this, arrayOfUsers);
// Attach the adapter to a ListView
ListView listView = (ListView) findViewById(R.id.lvItems);
listView.setAdapter(adapter);
// Add item to adapter
User newUser = new User("Nathan", R.drawable.logo);
adapter.add(newUser);