Custom List View
Creating a custom Adapter:
We have following steps to create a custom Adapter
1) Create a sub class of BaseAdapter
2) Declare the data objects we receive from Activity
3) Create a constructor with the declared objects
4) Override getCount method by passing the length of ListView
5) Override getItem method
6) Override getItemId method
7) Override getView method
i) Get LayoutInflater by using context
LayoutInflater inflater = LayoutInflater.from(context);
ii) Get View object from inflater by passing xml
View v = inflater.inflate(R.layout.list_item, parent, false);
iii) Identify all individual views
iv) Get data using position
v) Set the data to identified views
Ex:
public class MyAdapter extends BaseAdapter {
Context context;
String[] movies;
String[] cast;
public MyAdapter(Context context, String[] movies, String[] cast) {
this.context = context;
this.movies = movies;
this.cast = cast;
}
@Override
public int getCount() {
return movies.length;
}
@Override
public Object getItem(int position) {
return movies[position];
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.list_item, parent, false);
TextView textMovie = (TextView) view.findViewById(R.id.textView);
TextView textCast = (TextView) view.findViewById(R.id.textView2);
String movie = movies[position];
String castName = cast[position];
textMovie.setText(movie);
textCast.setText(castName);
return view;
}
}
Setting the above adapter to ListView in Activity:
ListView listView = (ListView)findViewById(R.id.listView);
String[] movies = {“Batman Triology”, “Harry Potter”, “Braveheart”, “The Patriot”, “Pompeii”, “Fast and Furious”,
“Die Hard”, “The Fifth element”, “X-Men”, “Transformers”, “Steve Jobs”};
String[] cast = {“Christian Bale”, “Daniel Radcliffe”, “Mel Gibson”, “Mel Gibson”, “Kit Harington”, “Paul Walker”,
“Bruce Willis”, “Bruce Willis”, “James McAvoy”, “Sam Witwicky”, “Michael fasbender”};
MyAdapter adapter = new MyAdapter(this, movies, cast);
listView.setAdapter(adapter);