item.java:
public class Item {
private String itemName;
private String itemDescription;
public Items(String name, String description) {
this.itemName = name;
this.itemDescription = description;
}
public String getItemName() {
return this.itemName;
}
public String getItemDescription() {
return itemDescription;
}
}
layout_list_view_row_items.xml
CustomListAdapter.java:
public class CustomListAdapter extends BaseAdapter {
private Context context; //context
private ArrayList- items; //data source of the list adapter
//public constructor
public CustomListAdapter(Context context, ArrayList
- items) {
this.context = context;
this.items = items;
}
@Override
public int getCount() {
return items.size(); //returns total of items in the list
}
@Override
public Object getItem(int position) {
return items.get(position); //returns list item at the specified position
}
@Override
public long getItemId(int position) {
return position;
}
@Override
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if (convertView == null) {
convertView = LayoutInflater.from(context).inflate(R.layout.layout_list_view_row_items, parent, false);
viewHolder = new ViewHolder(convertView);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
Item currentItem = (Item) getItem(position);
viewHolder.itemName.setText(currentItem.getItemName());
viewHolder.itemDescription.setText(currentItem.getItemDescription());
return convertView;
}
private class ViewHolder {
TextView itemName;
TextView itemDescription;
public ViewHolder(View view) {
itemName = (TextView)view.findViewById(R.id.text_view_item_name);
itemDescription = (TextView) view.findViewById(R.id.text_view_item_description);
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Setup the data source
ArrayList- itemsArrayList = new ArrayList
- (); // calls function to get items list
Item item = new Item("...","...");
Item item1 = new Item("...", "......");
itemsArrayList.add(item);
itemsArrayList.add(item1);
// instantiate the custom list adapter
CustomListAdapter adapter = new CustomListAdapter(this, itemsArrayList);
// get the ListView and attach the adapter
ListView itemsListView = (ListView) findViewById(R.id.list_view);
itemsListView.setAdapter(adapter);
}
}
出处:https://guides.codepath.com/android/Using-a-BaseAdapter-with-ListView