Display List item with Labels and index in Android

Hello Guys !!

Hope you are doing well...
In this tutorials, you will learn how to display list with labels and with index. In my previous post, I've explain about how to get Phone contact and display in listview in your android application.

Now I'm using the same concept here also. Get contacts from the phone and then display in Listview with labels and indexs.

Here are all the necessary java and xml files.


1. LabelListActivity.java

package com.pack.listlabel;

import java.util.ArrayList;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.widget.AlphabetIndexer;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class LabelListActivity extends Activity   {

private LinearLayout mIndexerLayout;
private ListView mListView;
private RelativeLayout mSectionToastLayout;
private TextView mSectionToastText;
private ArrayList<Glossary> glossaries = new ArrayList<Glossary>();
private String alphabet = "#ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private AlphabetIndexer mIndexer;
private InviteContactListAdapter mAdapter;
private int lastSelectedPosition = -1;

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_label_list);
getView();

}

private void getView() {
// TODO Auto-generated method stub
mIndexerLayout = (LinearLayout) findViewById(R.id.indexer_layout);
mListView = (ListView) findViewById(R.id.inviteContactsLV);
mSectionToastLayout = (RelativeLayout) findViewById(R.id.section_toast_layout);
mSectionToastText = (TextView) findViewById(R.id.section_toast_text);
getContactNumber();

}

public void getContactNumber() {
// TODO Auto-generated method stub
AsyncTask<Void, Void, Void> updateTask = new AsyncTask<Void, Void, Void>() {
ProgressDialog dialog = new ProgressDialog( LabelListActivity.this );
Cursor cursor;
@Override
protected void onPreExecute() {
// what to do before background task
dialog = ProgressDialog.show(LabelListActivity.this, "","Getting contact, please wait...", true);
}

@SuppressLint("InlinedApi")
@Override
protected Void doInBackground(Void... params) {
try {
for(int i = 0; i < alphabet.length(); i++) {
TextView letterTextView = new TextView(LabelListActivity.this);
letterTextView.setText(alphabet.charAt(i)+"");

letterTextView.setTextSize(14f);
letterTextView.setGravity(Gravity.CENTER);
letterTextView.setTextColor(Color.parseColor("#0075F8"));
LayoutParams paramss = new LinearLayout.LayoutParams(35, 0, 1.0f);
letterTextView.setLayoutParams(paramss);
letterTextView.setPadding(4, 0, 4, 0);
mIndexerLayout.addView(letterTextView);
mIndexerLayout.setBackgroundResource(R.drawable.letterslist_bg);
}
Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;

String _number = ContactsContract.CommonDataKinds.Phone.NUMBER;
String _name = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME;
String _sortKey = ContactsContract.CommonDataKinds.Phone.SORT_KEY_PRIMARY;
cursor = getContentResolver().query(uri,
new String[] { _name, _number, _sortKey }, null, null, "sort_key");
if (cursor.moveToFirst()) {
do {
String name = cursor.getString(0);
String number = cursor.getString(1);
String sortKey = getSortKey(cursor.getString(2));

Glossary glossary = new Glossary();
glossary.setName(name);
glossary.setNumber(number);
glossary.setSortKey(sortKey);
glossaries.add(glossary);

} while (cursor.moveToNext());
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();

}
return null;
}

@SuppressWarnings("deprecation")
@Override
protected void onPostExecute(Void result) {
// what to do when background task is completed
dialog.dismiss();
mAdapter = new InviteContactListAdapter(LabelListActivity.this, glossaries);
startManagingCursor(cursor);
mIndexer = new AlphabetIndexer(cursor, 2, alphabet);
mAdapter.setIndexer(mIndexer);

if(glossaries != null && glossaries.size() > 0) {
mListView.setAdapter(mAdapter);
mIndexerLayout.setOnTouchListener(mOnTouchListener);
}
};

@Override
protected void onCancelled() {
//dialog.dismiss();
super.onCancelled();
}
};
updateTask.execute((Void[]) null);
}

@SuppressLint("DefaultLocale")
private String getSortKey(String sortKeyString) {
String key = sortKeyString.substring(0, 1).toUpperCase();
if (key.matches("[A-Z]")) {
return key;
}
return "#";
}

private OnTouchListener mOnTouchListener = new OnTouchListener() {

@SuppressLint("NewApi")
@Override
public boolean onTouch(View v, MotionEvent event) {
float alphabetHeight = mIndexerLayout.getHeight();
float y = event.getY();
int sectionPosition = (int) ((y / alphabetHeight) / (1f / 27f));
if (sectionPosition < 0) {
sectionPosition = 0;
} else if (sectionPosition > 26) {
sectionPosition = 26;
}
if(lastSelectedPosition != sectionPosition) {
if(-1 != lastSelectedPosition){
((TextView) mIndexerLayout.getChildAt(lastSelectedPosition)).setBackgroundColor(getResources().getColor(android.R.color.transparent));
}
lastSelectedPosition = sectionPosition;
}
String sectionLetter = String.valueOf(alphabet.charAt(sectionPosition));
int position = mIndexer.getPositionForSection(sectionPosition);
TextView textView = (TextView) mIndexerLayout.getChildAt(sectionPosition);
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mIndexerLayout.setBackgroundResource(R.drawable.letterslist_bg);
textView.setBackgroundColor(getResources().getColor(R.color.letter_bg_color));
mSectionToastLayout.setVisibility(View.VISIBLE);
mSectionToastText.setText(sectionLetter);
mListView.smoothScrollToPositionFromTop(position,0,1);
break;
case MotionEvent.ACTION_MOVE:
mIndexerLayout.setBackgroundResource(R.drawable.letterslist_bg);
textView.setBackgroundColor(getResources().getColor(R.color.letter_bg_color));
mSectionToastLayout.setVisibility(View.VISIBLE);
mSectionToastText.setText(sectionLetter);
mListView.smoothScrollToPositionFromTop(position,0,1);
break;
case MotionEvent.ACTION_UP:
mSectionToastLayout.setVisibility(View.GONE);
default:
mSectionToastLayout.setVisibility(View.GONE);
break;
}
return true;
}

};

public boolean onQueryTextChange(String newText) {
return false;
}

public boolean onQueryTextSubmit(String query) {
return false;
}

public boolean onClose() {
return false;
}

protected boolean isAlwaysExpanded() {
return false;
}
}


2. InviteContactListAdapter.java


package com.pack.listlabel;

import java.util.ArrayList;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AlphabetIndexer;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;


public class InviteContactListAdapter extends BaseAdapter   {

private Context mContext;
private ArrayList<Glossary> glossariesList;
private LayoutInflater mInflater;
private AlphabetIndexer mIndexer;

public InviteContactListAdapter(Context context, ArrayList<Glossary> glossaries) {
super();
this.mContext = context;
this.glossariesList = glossaries;
mInflater = LayoutInflater.from(mContext);
}

@Override
public int getCount() {
return glossariesList.size();
}

@Override
public Object getItem(int position) {
return glossariesList.get(position);
}

@Override
public long getItemId(int position) {
return position;
}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if(convertView == null) {
convertView = mInflater.inflate(R.layout.contact_item, null);
holder = new ViewHolder();
holder.sortKeyLayout = (LinearLayout) convertView.findViewById(R.id.sort_key_layout);
holder.sortKey = (TextView) convertView.findViewById(R.id.sort_key);
holder.contactName = (TextView) convertView.findViewById(R.id.contact_name);

 
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}

 
Glossary glossary = glossariesList.get(position);
holder.contactName.setText(glossary.getName());
int section = mIndexer.getSectionForPosition(position);
if (position == mIndexer.getPositionForSection(section)) {
holder.sortKey.setText(glossary.getSortKey());
holder.sortKeyLayout.setVisibility(View.VISIBLE);
} else {
holder.sortKeyLayout.setVisibility(View.GONE);
}

return convertView;
}
/**

* @param indexer
*/
public void setIndexer(AlphabetIndexer indexer) {
mIndexer = indexer;
}

private static class ViewHolder {
LinearLayout sortKeyLayout;
TextView sortKey;
TextView contactName;
 
}
}


3. Glossary.java

package com.pack.listlabel;

public class Glossary {
 
private String name;
private String number;
private String sortKey;
public String getNumber() {
return number;
}

public void setNumber(String number) {
this.number = number;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getSortKey() {
return sortKey;
}

public void setSortKey(String sortKey) {
this.sortKey = sortKey;
}

}


Here are the xml files.

1. activity_label_list.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#fff"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"   android:background="#F47070"
        android:text="Contact List with label and index"
        android:textColor="#000" android:padding="10dp"
        android:textSize="16sp" />

    <ListView
        android:id="@+id/inviteContactsLV"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/text"
        android:cacheColorHint="#00000000"
        android:divider="#e6e6e6"
        android:dividerHeight="1dp" >
    </ListView>

    <LinearLayout
        android:id="@+id/indexer_layout"
        android:layout_width="40dp"
        android:layout_height="match_parent"
        android:layout_alignParentRight="true"
        android:layout_marginBottom="5dp"
        android:layout_marginRight="0dp"
        android:layout_marginTop="1dp"
        android:background="#fff"
        android:gravity="center"
        android:orientation="vertical" />

    <RelativeLayout
        android:id="@+id/section_toast_layout"
        android:layout_width="50dip"
        android:layout_height="50dip"
        android:layout_centerInParent="true"
        android:background="@drawable/current_letter_bubble"
        android:visibility="gone" >

        <TextView
            android:id="@+id/section_toast_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:textColor="#8E8E8E"
            android:textSize="30sp" />
    </RelativeLayout>

</RelativeLayout>


2. contact_item.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#fff"
    android:orientation="vertical" >

    <LinearLayout
        android:id="@+id/sort_key_layout"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="#ccc"
        android:padding="4dp" >

        <TextView
            android:id="@+id/sort_key"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:layout_marginLeft="10dip"
            android:textColor="#000000" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:padding="10dp"
        android:weightSum="2" >

        <TextView
            android:id="@+id/contact_name"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:layout_weight="1.6"
            android:textColor="#000"
            android:textSize="16sp" />

         
    </LinearLayout>

</LinearLayout>




Here is the output of the program :







Happy Coding !!

Comments

Popular posts from this blog

Carousel view in Android

Get Phone Contacts and display in Listview in Android

Draw Pie Chart using Canvas and Third party Library in Android