Monday, April 30, 2012

Android Alphabet ListView like contacts

Android Alphabet ListView like contacts
Here is the code for list with alpha bite selection please go through 


1. Main.xml
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <RelativeLayout  
  3.     xmlns:android="http://schemas.android.com/apk/res/android"  
  4.     android:layout_width="fill_parent"  
  5.     android:layout_height="fill_parent">  
  6. <ListView android:id="@+id/myListView"  
  7.     android:layout_width="fill_parent"  
  8.     android:layout_height="fill_parent"  
  9. />  
  10. <android.test.SideBar  
  11.     android:id = "@+id/sideBar"  
  12.     android:layout_height="fill_parent"  
  13.     android:layout_width="22px"  
  14.     android:layout_alignParentRight="true"  
  15. />  
  16. </RelativeLayout>  
2. listview_row.xml
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout  
  3.     xmlns:android="http://schemas.android.com/apk/res/android"  
  4.     android:orientation="vertical"  
  5.     android:layout_width="fill_parent"  
  6.     android:layout_height="wrap_content">  
  7. <LinearLayout  
  8.     android:id="@+id/section"  
  9.     android:layout_width="fill_parent"  
  10.     android:layout_height="wrap_content"  
  11. />  
  12. <TextView android:id="@+id/textView"  
  13.     android:layout_width="wrap_content"  
  14.     android:layout_height="80sp"  
  15.     android:textSize="45sp"  
  16. />  
  17. </LinearLayout>  
3. MyAdapter.java
  1. package android.test;  
  2. import java.util.ArrayList;  
  3. import android.app.Activity;  
  4. import android.content.Context;  
  5. import android.graphics.Color;  
  6. import android.view.Gravity;  
  7. import android.view.LayoutInflater;  
  8. import android.view.View;  
  9. import android.view.ViewGroup;  
  10. import android.widget.BaseAdapter;  
  11. import android.widget.LinearLayout;  
  12. import android.widget.SectionIndexer;  
  13. import android.widget.TextView;  
  14. public class MyAdapter extends BaseAdapter implements SectionIndexer {  
  15.     private ArrayList<String> stringArray;  
  16.     private Context context;  
  17.     public MyAdapter(Context _context, ArrayList<String> arr) {  
  18.         stringArray = arr;  
  19.         context = _context;  
  20.     }  
  21.     public int getCount() {  
  22.         return stringArray.size();  
  23.     }  
  24.     public Object getItem(int arg0) {  
  25.         return stringArray.get(arg0);  
  26.     }  
  27.     public long getItemId(int arg0) {  
  28.         return 0;  
  29.     }  
  30.     public View getView(int position, View v, ViewGroup parent) {  
  31.         LayoutInflater inflate = ((Activity) context).getLayoutInflater();  
  32.         View view = (View) inflate.inflate(R.layout.listview_row, null);  
  33.         LinearLayout header = (LinearLayout) view.findViewById(R.id.section);  
  34.         String label = stringArray.get(position);  
  35.         char firstChar = label.toUpperCase().charAt(0);  
  36.         if (position == 0) {  
  37.             setSection(header, label);  
  38.         } else {  
  39.             String preLabel = stringArray.get(position - 1);  
  40.             char preFirstChar = preLabel.toUpperCase().charAt(0);  
  41.             if (firstChar != preFirstChar) {  
  42.                 setSection(header, label);  
  43.             } else {  
  44.                 header.setVisibility(View.GONE);  
  45.             }  
  46.         }  
  47.         TextView textView = (TextView) view.findViewById(R.id.textView);  
  48.         textView.setText(label);  
  49.         return view;  
  50.     }  
  51.     private void setSection(LinearLayout header, String label) {  
  52.         TextView text = new TextView(context);  
  53.         header.setBackgroundColor(0xffaabbcc);  
  54.         text.setTextColor(Color.WHITE);  
  55.         text.setText(label.substring(01).toUpperCase());  
  56.         text.setTextSize(20);  
  57.         text.setPadding(5000);  
  58.         text.setGravity(Gravity.CENTER_VERTICAL);  
  59.         header.addView(text);  
  60.     }  
  61.     public int getPositionForSection(int section) {  
  62.         if (section == 35) {  
  63.             return 0;  
  64.         }  
  65.         for (int i = 0; i < stringArray.size(); i++) {  
  66.             String l = stringArray.get(i);  
  67.             char firstChar = l.toUpperCase().charAt(0);  
  68.             if (firstChar == section) {  
  69.                 return i;  
  70.             }  
  71.         }  
  72.         return -1;  
  73.     }  
  74.     public int getSectionForPosition(int arg0) {  
  75.         return 0;  
  76.     }  
  77.     public Object[] getSections() {  
  78.         return null;  
  79.     }  
  80. }  
4.  SideBar.java
  1. package android.test;  
  2. import android.content.Context;  
  3. import android.graphics.Canvas;  
  4. import android.graphics.Paint;  
  5. import android.util.AttributeSet;  
  6. import android.view.MotionEvent;  
  7. import android.view.View;  
  8. import android.widget.ListView;  
  9. import android.widget.SectionIndexer;  
  10. public class SideBar extends View {  
  11.     private char[] l;  
  12.     private SectionIndexer sectionIndexter = null;  
  13.     private ListView list;  
  14.     private final int m_nItemHeight = 29;  
  15.     public SideBar(Context context) {  
  16.         super(context);  
  17.         init();  
  18.     }  
  19.     public SideBar(Context context, AttributeSet attrs) {  
  20.         super(context, attrs);  
  21.         init();  
  22.     }  
  23.     private void init() {  
  24.         l = new char[] { 'A''B''C''D''E''F''G''H''I''J''K''L''M''N''O''P''Q''R''S',  
  25.                 'T''U''V''W''X''Y''Z' };  
  26.         setBackgroundColor(0x44FFFFFF);  
  27.     }  
  28.     public SideBar(Context context, AttributeSet attrs, int defStyle) {  
  29.         super(context, attrs, defStyle);  
  30.         init();  
  31.     }  
  32.     public void setListView(ListView _list) {  
  33.         list = _list;  
  34.         sectionIndexter = (SectionIndexer) _list.getAdapter();  
  35.     }  
  36.     public boolean onTouchEvent(MotionEvent event) {  
  37.         super.onTouchEvent(event);  
  38.         int i = (int) event.getY();  
  39.         int idx = i / m_nItemHeight;  
  40.         if (idx >= l.length) {  
  41.             idx = l.length - 1;  
  42.         } else if (idx < 0) {  
  43.             idx = 0;  
  44.         }  
  45.         if (event.getAction() == MotionEvent.ACTION_DOWN || event.getAction() == MotionEvent.ACTION_MOVE) {  
  46.             if (sectionIndexter == null) {  
  47.                 sectionIndexter = (SectionIndexer) list.getAdapter();  
  48.             }  
  49.             int position = sectionIndexter.getPositionForSection(l[idx]);  
  50.             if (position == -1) {  
  51.                 return true;  
  52.             }  
  53.             list.setSelection(position);  
  54.         }  
  55.         return true;  
  56.     }  
  57.     protected void onDraw(Canvas canvas) {  
  58.         Paint paint = new Paint();  
  59.         paint.setColor(0xFFA6A9AA);  
  60.         paint.setTextSize(20);  
  61.         paint.setTextAlign(Paint.Align.CENTER);  
  62.         float widthCenter = getMeasuredWidth() / 2;  
  63.         for (int i = 0; i < l.length; i++) {  
  64.             canvas.drawText(String.valueOf(l[i]), widthCenter, m_nItemHeight + (i * m_nItemHeight), paint);  
  65.         }  
  66.         super.onDraw(canvas);  
  67.     }  
  68. }  
5. Main.java
  1. package android.test;  
  2. import java.util.ArrayList;  
  3. import android.app.Activity;  
  4. import android.os.Bundle;  
  5. import android.widget.ListView;  
  6. public class Main extends Activity {  
  7.     /** Called when the activity is first created. */  
  8.     @Override  
  9.     public void onCreate(Bundle savedInstanceState) {  
  10.         super.onCreate(savedInstanceState);  
  11.         setContentView(R.layout.main);  
  12.         ListView list = (ListView) findViewById(R.id.myListView);  
  13.         ArrayList<String> stringList = InitListViewData();  
  14.         MyAdapter adapter = new MyAdapter(this, stringList);  
  15.         list.setAdapter(adapter);  
  16.         SideBar indexBar = (SideBar) findViewById(R.id.sideBar);  
  17.         indexBar.setListView(list);  
  18.     }  
  19.     private ArrayList<String> InitListViewData() {  
  20.         ArrayList<String> stringList = new ArrayList<String>();  
  21.         stringList.add("aback");  
  22.         stringList.add("abash");  
  23.         stringList.add("abbey");  
  24.         stringList.add("abhor");  
  25.         stringList.add("abide");  
  26.         stringList.add("abuse");  
  27.         stringList.add("candidate");  
  28.         stringList.add("capture");  
  29.         stringList.add("careful");  
  30.         stringList.add("catch");  
  31.         stringList.add("cause");  
  32.         stringList.add("celebrate");  
  33.         stringList.add("forever");  
  34.         stringList.add("fable");  
  35.         stringList.add("fidelity");  
  36.         stringList.add("fox");  
  37.         stringList.add("funny");  
  38.         stringList.add("fail");  
  39.         stringList.add("jail");  
  40.         stringList.add("jade");  
  41.         stringList.add("jailor");  
  42.         stringList.add("january");  
  43.         stringList.add("jasmine");  
  44.         stringList.add("jazz");  
  45.         stringList.add("zero");  
  46.         stringList.add("zoo");  
  47.         stringList.add("zeus");  
  48.         stringList.add("zebra");  
  49.         stringList.add("zest");  
  50.         stringList.add("zing");  
  51.         return stringList;  
  52.     }  
  53. }  

29 comments:

Anonymous said...

Thanks ... best article on net ...

Unknown said...

Thanks for your comments

Anonymous said...

nice tutorial.... worked for me..

Unknown said...

Thank you very much guys for visiting
the blog .... keep in touch

Unknown said...

Actually Iam facing a problem with this code... the entire alphabet list is not visble on differnt mobile screens.. i tried lot of methods bt i didn't get it.. So, please help me... Thanks in advance...

Unknown said...

private void setSection(LinearLayout header, String label) {
TextView text = new TextView(context);
header.setBackgroundColor(0xffaabbcc);
text.setTextColor(Color.WHITE);
text.setText(label.substring(0, 1).toUpperCase());
text.setTextSize(20);
text.setPadding(5, 0, 0, 0);
text.setGravity(Gravity.CENTER_VERTICAL);
header.removeAllViews(); // <-- remove previous added
header.addView(text);
header.setVisibility(View.VISIBLE); // <-- show it
}

hari said...

Hi nice tutorial. its worked for me very well :) :) :)

but i have one problem with side bar
android.test.bar class not found exception what it means
plz help me i need side bar also
Thanks in advance...

Unknown said...

Kindly check the android.test.bar is here I used in main.xml replace the android.test with your package name and test

Unknown said...

Thanks a lot for this tutorial !

@tej deep:
You can set the sidebar height in SideBar.java line 15.

Now you need to know the correct value for each screen resolution.

Unknown said...

Nice Tutorial.
I have one Question.
I am using your code in my app.
And I want to insert new listItem dynamically into your provided list and item should be placed into respective section.How can I do this.
Will u like to give me a way

Anonymous said...

Excellent article!

Niyaz said...

Pefect example..thank u soo much

Anonymous said...

Thanks for this post, it's help me

Unknown said...

Excellent article, ca m'a aidé enormement encore merci

Kruti Gajjar said...

Hi ! I am using your code in my app but i get this error :

06-21 11:13:29.805: E/AndroidRuntime(18451): java.lang.ClassCastException: android.widget.SimpleCursorAdapter cannot be cast to android.widget.SectionIndexer
06-21 11:13:29.805: E/AndroidRuntime(18451): at com.indusa.erpdemo.adpater.SideBar.onTouchEvent(SideBar.java:49)

Can you guide me to resolve this ?

Thanks :)

Unknown said...

This code give me error Like:

07-16 12:31:41.907: E/AndroidRuntime(25868): FATAL EXCEPTION: main
07-16 12:31:41.907: E/AndroidRuntime(25868): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.sidebar/com.example.sidebar.SideBarActivity}: android.view.InflateException: Binary XML file line #11: Error inflating class android.test.SideBar
07-16 12:31:41.907: E/AndroidRuntime(25868): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1955)
07-16 12:31:41.907: E/AndroidRuntime(25868): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1980)
07-16 12:31:41.907: E/AndroidRuntime(25868): at android.app.ActivityThread.access$600(ActivityThread.java:122)
07-16 12:31:41.907: E/AndroidRuntime(25868): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1146)
07-16 12:31:41.907: E/AndroidRuntime(25868): at android.os.Handler.dispatchMessage(Handler.java:99)
07-16 12:31:41.907: E/AndroidRuntime(25868): at android.os.Looper.loop(Looper.java:137)
07-16 12:31:41.907: E/AndroidRuntime(25868): at android.app.ActivityThread.main(ActivityThread.java:4340)
07-16 12:31:41.907: E/AndroidRuntime(25868): at java.lang.reflect.Method.invokeNative(Native Method)
07-16 12:31:41.907: E/AndroidRuntime(25868): at java.lang.reflect.Method.invoke(Method.java:511)
07-16 12:31:41.907: E/AndroidRuntime(25868): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
07-16 12:31:41.907: E/AndroidRuntime(25868): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
07-16 12:31:41.907: E/AndroidRuntime(25868): at dalvik.system.NativeStart.main(Native Method)
07-16 12:31:41.907: E/AndroidRuntime(25868): Caused by: android.view.InflateException: Binary XML file line #11: Error inflating class android.test.SideBar
07-16 12:31:41.907: E/AndroidRuntime(25868): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:691)
07-16 12:31:41.907: E/AndroidRuntime(25868): at android.view.LayoutInflater.rInflate(LayoutInflater.java:739)
07-16 12:31:41.907: E/AndroidRuntime(25868): at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
07-16 12:31:41.907: E/AndroidRuntime(25868): at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
07-16 12:31:41.907: E/AndroidRuntime(25868): at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
07-16 12:31:41.907: E/AndroidRuntime(25868): at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:251)
07-16 12:31:41.907: E/AndroidRuntime(25868): at android.app.Activity.setContentView(Activity.java:1835)
07-16 12:31:41.907: E/AndroidRuntime(25868): at com.example.sidebar.SideBarActivity.onCreate(SideBarActivity.java:14)
07-16 12:31:41.907: E/AndroidRuntime(25868): at android.app.Activity.performCreate(Activity.java:4465)
07-16 12:31:41.907: E/AndroidRuntime(25868): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
07-16 12:31:41.907: E/AndroidRuntime(25868): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1919)
07-16 12:31:41.907: E/AndroidRuntime(25868): ... 11 more
07-16 12:31:41.907: E/AndroidRuntime(25868): Caused by: java.lang.ClassNotFoundException: android.test.SideBar
07-16 12:31:41.907: E/AndroidRuntime(25868): at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:61)
07-16 12:31:41.907: E/AndroidRuntime(25868): at java.lang.ClassLoader.loadClass(ClassLoader.java:501)
07-16 12:31:41.907: E/AndroidRuntime(25868): at java.lang.ClassLoader.loadClass(ClassLoader.java:461)
07-16 12:31:41.907: E/AndroidRuntime(25868): at android.view.LayoutInflater.createView(LayoutInflater.java:552)
07-16 12:31:41.907: E/AndroidRuntime(25868): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:680)
07-16 12:31:41.907: E/AndroidRuntime(25868): ... 21 more

jagdishnagar said...

Sidebar class not found exception plz help

Unknown said...

Nice code but when i run my application it was force to close.

Anonymous said...

Thanks for sharing code. its working fine.
How can i add scroll view above side bar view in layout as all characters are not displayed .

Unknown said...

tnx for post, how can i display the current char while scrolling like it is displayed while scrolling the contacts

Kris Groove said...

How make that with this GridView?

Anonymous said...

Section headers seem to disappear when scrolling up and down in long lists - how do you overcome that?

Anonymous said...

How to get GetSections for this?

Unknown said...

Hello,

Thanks for this great article.
I have used this. Only one issue which i found is that this is not showing full contacts. Only one contact with group. Also group name is under contact name.

Please suggest.

Unknown said...

Hello,

I have found my mistake. I have taken textview inside section layout.

Now my code is running well.
Very very thanks fro this code.

I have used this code in a app where i have to use all phone contacts. Have you any idea that how can i get all numbers if a contact have more than one numbers.

Anonymous said...

nice tutorial, but can anyone tell me how to use this for cursor adapter.

Unknown said...

thank you so much

Anonymous said...

Awesome tutorial. thanks a lot. Can you please tell me how to make side bar to fit to any mobile screen. Thanks in advance.

Unknown said...

you are awesome man. thanks for making my task easy.