Home > DeveloperSection > Articles > Sorting list with side bar

Sorting list with side bar


Android Android  Sorting  ListView 
Ratings:
0 Comment(s)
 1069  View(s)
Rate this:

Sorting list with side bar


Previously, we learn about how to Creating custom and compound Views in Android (Creating custom and compound Views in Android). Now we see how to Sorting list with side bar in Listview.


In this article we are going to learn, how to get the sorted list of items based on alphabets selected from alphabet list inside the sidebar.


Android provides SectionIndexer interface which help to get position for search custom listview adapter.

Interface that may implemented on Adapter to enable fast scrolling between sections of an AbsListView.

After finishing my code and UI, activity looking like this

1.      Create an Android project on eclipse or Android visual Studio.

2.      Add a class for make side bar selection event.

 

@SuppressLint("DefaultLocale")

public class SideBar extends View {

      private SectionIndexer sectionIndexter = null;

      private ListView list;

      private int m_nItemHeight = 9;

      ArrayList<Character> charList;

 

      int count = 0;

 

      // Create constructor for get Activity context

      public SideBar(Context context, AttributeSet attrs) {

            super(context, attrs);

            init();

      }

 

      @SuppressLint("DefaultLocale")

      private void init() {

 

            charList = new ArrayList<Character>();

            // Add item for search in listview on sidebar

            for (int i = 65; i < 91; i++)

                  charList.add((char) i);

 

            setBackgroundColor(0x44FFFFFF);

      }

 

      // Set list view from my listview

      public void setListView(ListView _list) {

            try {

                  list = _list;

 

                  sectionIndexter = (SectionIndexer) _list.getAdapter();

            } catch (Exception ex) {

            }

 

      }

 

      @Override

      @SuppressLint("DefaultLocale")

      public boolean onTouchEvent(MotionEvent event) {

            try {

                  // On Side bar index touch or click

                  super.onTouchEvent(event);

                  int i = (int) event.getY();

                  int idx = i / m_nItemHeight;

                  if (idx >= charList.size()) {

                        idx = charList.size() - 1;

                  } else if (idx < 0) {

                        idx = 0;

                  }

                  if (event.getAction() == MotionEvent.ACTION_DOWN

                              || event.getAction() == MotionEvent.ACTION_MOVE) {

                        if (sectionIndexter == null) {

                              sectionIndexter = (SectionIndexer) list.getAdapter();

                        }

                        //

                        int position = sectionIndexter.getPositionForSection(charList

                                    .get(idx));

                        if (position == -1) {

                              return true;

                        }

                        // Set toast message after select item

                        final Toast toast = Toast.makeText(getContext(),

                             String.valueOf(charList.get(idx)), Toast.LENGTH_SHORT);

                        toast.show();

                        toast.setGravity(Gravity.CENTER, 0, 0);

                        new CountDownTimer(500, 500) {

                              @Override

                              public void onTick(long millisUntilFinished) {

                                    toast.show();

                              }

 

                              @Override

                              public void onFinish() {

                                    toast.cancel();

                              }

                        }.start();

                        // Set Selection item position

                        list.setSelection(position);

 

                  }

            } catch (Exception ex) {

 

            }

            return true;

      }

 

      @Override

      @SuppressLint("DrawAllocation")

      protected void onDraw(Canvas canvas) {

            Paint paint = new Paint();

            paint.setColor(Color.parseColor("#1A76C1"));

            paint.setTextSize(14);

 

            paint.setTextAlign(Paint.Align.CENTER);

            float widthCenter = getMeasuredWidth() / 2;

            for (int i = 0; i < charList.size(); i++) {

 

                  WindowManager wm = (WindowManager) getContext().getSystemService(

                              Context.WINDOW_SERVICE);

                  Display display = wm.getDefaultDisplay();

                  @SuppressWarnings("deprecation")

                  int height = display.getHeight() - 90;

                  m_nItemHeight = height / 26;

                  paint.setTextSize(height / 26);

 

                  canvas.drawText(String.valueOf(charList.get(i)), widthCenter,

                              m_nItemHeight + (i * m_nItemHeight), paint);

            }

 

            super.onDraw(canvas);

      } 

3.      Add listview in your layout xml. i.e

 

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    tools:context=".MainActivity" >

 

    <ListView

        android:id="@+id/myListView"

        android:layout_width="fill_parent"

        android:layout_height="wrap_content" >

    </ListView>

 

    <!-- Add layout to show in side bar -->

    <android.test.SideBar

        android:id="@+id/sideBar"

        android:layout_width="33px"

        android:layout_height="wrap_content"

        android:layout_alignParentRight="true"

        android:layout_marginLeft="25sp"

        android:layout_marginRight="1sp"

        android:background="#FFFFFF"

        android:fadeScrollbars="true" />

 

</RelativeLayout> 

4.      Add xml layout file to show item of custom listview

  <?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:layout_gravity="center"

    android:orientation="horizontal" >

 

    <ImageView

        android:id="@+id/myIcon"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:src="@drawable/ic_launcher" />

 

    <TextView

        android:id="@+id/tvTitle"

        android:layout_marginTop="15sp"

        android:layout_marginLeft="10sp"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:gravity="center"

         />

 

</LinearLayout>

 

5.      Now paste following to code in MainActicity. class

 

package com.example.listsortingbyname;

 

import java.util.ArrayList;

import java.util.List;

 

import android.os.Bundle;

import android.annotation.SuppressLint;

import android.app.Activity;

import android.test.SideBar;

import android.view.Menu;

import android.widget.ListView;

 

public class MainActivity extends Activity {

            ListView listView;

            List<String> myList;

 

            @SuppressLint("NewApi")

            @Override

            protected void onCreate(Bundle savedInstanceState) {

                        super.onCreate(savedInstanceState);

                        setContentView(R.layout.activity_main);

                        listView = (ListView) findViewById(R.id.myListView);

 

                        // Create an object of a class and find his id from xml layout

                        SideBar indexBar = (SideBar) findViewById(R.id.sideBar);

                        // set listview to sort in side bar

                        indexBar.setListView(listView);

                        myList = new ArrayList<String>();

                        myList.add("A");myList.add("Aa");myList.add("Aaa");     myList.add("Aaaa");            myList.add("Aaaaa");

                        myList.add("B");myList.add("Bb");myList.add("Bbb");     myList.add("Bbbb");            myList.add("Bbbbb");

                        myList.add("C");myList.add("Cc");myList.add("Ccc");            myList.add("D");myList.add("Dd");myList.add("Ddd");

                        myList.add("E");myList.add("Ee");myList.add("Eee");            myList.add("F");myList.add("Ff");myList.add("G");

                        myList.add("Gg");myList.add("H");myList.add("Hh");myList.add("Hhh");myList.add("I");

                        myList.add("Ii");myList.add("Iii");            myList.add("J");myList.add("Jj");myList.add("K");myList.add("Kk");

                        myList.add("L");myList.add("Ll");myList.add("M");myList.add("Mm");myList.add("N");            myList.add("Nn");

                        myList.add("Nnn");            myList.add("O");myList.add("Oo");myList.add("Ooo");myList.add("P");

                        myList.add("Ppp");    myList.add("Q");myList.add("Qq");myList.add("Qqq");            myList.add("R");

                        myList.add("Rr");myList.add("S");myList.add("T");myList.add("U");myList.add("V");

                        myList.add("W");myList.add("X");myList.add("Y");myList.add("Z");myList.add("Zz");

                        // bind data in adapter class

                        MyListAdapter adapter = new MyListAdapter(this, myList);

                        // set adapter in listview

                        listView.setAdapter(adapter);

            }

 

            @Override

            public boolean onCreateOptionsMenu(Menu menu) {

                        // Inflate the menu; this adds items to the action bar if it is present.

                        getMenuInflater().inflate(R.menu.main, menu);

                        return true;

            }

} 

6.      Create an adapter class to bind data in a view and implements this class with SectionIndexer.

 

package com.example.listsortingbyname;

 

import java.util.List;

 

import android.app.AlertDialog;

import android.content.Context;

import android.content.DialogInterface;

import android.graphics.Color;

import android.graphics.drawable.Drawable;

import android.os.CountDownTimer;

import android.view.Gravity;

import android.view.LayoutInflater;

import android.view.View;

import android.view.View.OnClickListener;

import android.view.View.OnLongClickListener;

import android.view.ViewGroup;

import android.widget.BaseAdapter;

import android.widget.ImageView;

import android.widget.LinearLayout;

import android.widget.SectionIndexer;

import android.widget.TextView;

import android.widget.Toast;

 

// Async class to fill data in my listview

public class MyListAdapter extends BaseAdapter implements SectionIndexer {

 

            private Context context;

            LayoutInflater inflater;

            List<String> myList;

 

            public MyListAdapter(Context _context, List<String> arr) {

                        myList = arr;

                        context = _context;

                        inflater = LayoutInflater.from(context);

 

            }

 

            // hold view in class

            private class ViewHolder {

                        TextView tvTitle;

                        ImageView imgGroupIcon;

 

            }

 

            @Override

            public int getCount() {

                        return myList.size();

            }

 

            @Override

            public Object getItem(int arg0) {

                        return myList.get(arg0);

            }

 

            @Override

            public long getItemId(int arg0) {

                        return 0;

            }

 

            @Override

            public View getView(final int position, View view, ViewGroup parent) {

                        final ViewHolder holder;

 

                        if (view == null) {

                                    holder = new ViewHolder();

                                    view = inflater.inflate(R.layout.listview_item, null);

                                    // Locate the TextViews in listview_item.xml

                                    holder.tvTitle = (TextView) view.findViewById(R.id.tvTitle);

                                    holder.imgGroupIcon = (ImageView) view.findViewById(R.id.myIcon);

                                   

                                    view.setTag(holder);

                        } else {

                                    holder = (ViewHolder) view.getTag();

                        }

 

                        holder.tvTitle.setText(myList.get(position));

 

                        return view;

            }

// return selected itrm position

            @Override

            public int getPositionForSection(int section) {

 

                        if (section == 35) {

                                    return 35;

                        }

                        for (int i = 0; i < myList.size(); i++) {

                                    String l = myList.get(i);

                                    char firstChar = l.toUpperCase().charAt(0);

                                    if (firstChar == section) {

                                                return i;

                                    }

                        }

 

                        return -1;

            }

 

            @Override

            public int getSectionForPosition(int arg0) {

                        return 0;

            }

 

            @Override

            public Object[] getSections() {

                        return null;

            }

} 

Now run your application.

   

 


Don't want to miss updates? Please click the below button!

Follow MindStick