Sunday 12 August 2012

How to Extend Array Adapters to Create customized listView ?


The answer i got in the web to the above question is "SCRATCH YOUR OWN ITCH".Hence,am putting on this post so that people who are struggling to get this thing right,need not have to spend lot of time scratching their own itch..:p.

You can use the below code to use ListViews along with other views in the layout or ListView alone.
Lets get Started??.. Yeah.
There are three simple steps in creating a customized List View

  • Get the ListView in your layout by specifying its resource ID
  • Get the instance of your own ArrayAdapter class
  • Bind ListView to the adapter



Get the ListView in your layout by specifying its resource ID

Get the ListView instance in layout by its ID.

// Get the list View
mCustomListView = (ListView) findViewById(R.id.db_menu);

Get the instance of your own ArrayAdapter class and Bind ListView to the adapter

We can  combine steps 2 and 3 and implement it as below

// set the Adapter
mCustomListView.setAdapter(new DashBoardListAdapter(
getApplicationContext(), R.layout.dashboard_custom_list));

the argument R.layout.dashboard_custom_list is the resource ID of your customized view which has to created separately to achieve customization, not your ListView ID in the main layout.

Your Array adapter class should override getView method and getCount method of the parent.
Here's the implementation,
-------------------------------------------------------------------------------------------------
class DashBoardListAdapter extends ArrayAdapter<String> {
private Context mContext;
private String[] mTitle_content, mDesc_content;
private TextView mTitle, mDescription;

public DashBoardListAdapter(Context context, int layout) {
super(context, layout);
this.mContext = context;
setContentValues();
}

@Override
public int getCount() {
return mTitle_content.length;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v;
if (null == convertView) {
LayoutInflater inflator = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflator.inflate(R.layout.dashboard_custom_list, null);
} else {
v = convertView;
}
mTitle = (TextView) v.findViewById(R.id.db_topic);
mTitle.setText(mTitle_content[position]);
mDescription = (TextView) v.findViewById(R.id.db_description);
mDescription.setText(mDesc_content[position]);
return v;
}

private void setContentValues() {
mTitle_content = mContext.getResources().getStringArray(
R.array.bashboard_menu);
mDesc_content = mContext.getResources().getStringArray(
R.array.db_list_desc);
-------------------------------------------------------------------------------------------------------

Thats it,your listView is ready to use.In the listView by taking a seperate layout,i have changed the textView appearance in the listView and it looks lyk,



Happy Coding,
-Rajeev


No comments:

Post a Comment

Note: only a member of this blog may post a comment.