How to Add Section Indexers in a Android List View
Crete the Adapter for list view .
public class ContactsAdapter extends BaseAdapter implements SectionIndexer {
Context context;
String[] strings;
String[] sections ;
HashMap alphaIndexer;
public ContactsAdapter(Context context, String[] strings) {
this.context = context;
this.strings = strings;
alphaIndexer = new HashMap();
int size = strings.length;
for (int x = 0; x < size; x++) {
String s = strings[x];
String ch = s.substring(0, 1);
ch = ch.toUpperCase();
if (!alphaIndexer.containsKey(ch))
alphaIndexer.put(ch, x);
}
Set sectionLetters = alphaIndexer.keySet();
ArrayList sectionList = new ArrayList<>(sectionLetters);
Collections.sort(sectionList);
sections = new String[sectionList.size()];
sectionList.toArray(sections);
}
@Override
public int getCount() {
return strings.length;
}
@Override
public Object getItem(int position) {
return strings[position];
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = LayoutInflater.from(context).inflate(R.layout.main, parent, false);
holder = new ViewHolder();
holder.text = (TextView) convertView.findViewById(R.id.tv_contact);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.text.setText(strings[position]);
return convertView;
}
@Override
public Object[] getSections() {
return sections;
}
@Override
public int getPositionForSection(int sectionIndex) {
return alphaIndexer.get(sections[sectionIndex]);
}
@Override
public int getSectionForPosition(int position) {
return 0;
}
static class ViewHolder {
TextView text;
}
}
list Row for your adapter class
In your activity Initialize the list view and set adapter thats all
public class Registration extends BaseActivity{
private ListView listview;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
listview = (ListView) findViewById(R.id.listView);
ContactsAdapter contactsAdapter = new ContactsAdapter(Registration.this,YourArry[]);
listview.setAdapter(contactsAdapter);
listview.setFastScrollEnabled(true);
}
}
thats all ,
Comments
Post a Comment