Thursday 4 April 2013

IndexableListview Example

Create a java file name CustomListIndex.java
=============================
package com.index.table;

import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.TextView;

import com.index.table.to.Book;

public class CustomListIndex extends Activity {

    private static final String TAG = CustomListIndex.class.getSimpleName();

    protected GestureDetector mGestureDetector;

    protected Vector<Book> userVector;

    protected int totalListSize = 0;
    
    /**
     * list with items for side index
     */
    private ArrayList<Object[]> indexList = null;

    /**
     * list with row number for side index
     */
    protected List<Integer> dealList = new ArrayList<Integer>();

    /**
     * height of left side index
     */
    protected int sideIndexHeight;

    /**
     * number of items in the side index
     */
    private int indexListSize;

    /**
     * x and y coordinates within our side index
     */
    protected static float sideIndexX;
    protected static float sideIndexY;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        Log.i(TAG, TAG);
    }

    /**
     * displayListItem is method used to display the row from the list on scrool
     * or touch.
     */
    public void displayListItem() {
        
        // compute number of pixels for every side index item
        double pixelPerIndexItem = (double) sideIndexHeight / indexListSize;

        // compute the item index for given event position belongs to
        int itemPosition = (int) (sideIndexY / pixelPerIndexItem);

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

        if (itemPosition < 0) {
            itemPosition = 0;
        } else if (itemPosition >= dealList.size()) {
            itemPosition = dealList.size() - 1;
        }

        int listLocation = dealList.get(itemPosition) + itemPosition;

        if (listLocation > totalListSize) {
            listLocation = totalListSize;
        }

        listView.setSelection(listLocation);
    }

    /**
     * getListArrayIndex consists of index details, to navigate through out the index.
     * 
     * @param strArr , index values
     * @return ArrayList object
     */
    private ArrayList<Object[]> getListArrayIndex(String[] strArr) {
        ArrayList<Object[]> tmpIndexList = new ArrayList<Object[]>();
        Object[] tmpIndexItem = null;

        int tmpPos = 0;
        String tmpLetter = "";
        String currentLetter = null;

        for (int j = 0; j < strArr.length; j++) {
            currentLetter = strArr[j];

            // every time new letters comes
            // save it to index list
            if (!currentLetter.equals(tmpLetter)) {
                tmpIndexItem = new Object[3];
                tmpIndexItem[0] = tmpLetter;
                tmpIndexItem[1] = tmpPos - 1;
                tmpIndexItem[2] = j - 1;

                tmpLetter = currentLetter;
                tmpPos = j + 1;
                tmpIndexList.add(tmpIndexItem);
            }
        }

        // save also last letter
        tmpIndexItem = new Object[3];
        tmpIndexItem[0] = tmpLetter;
        tmpIndexItem[1] = tmpPos - 1;
        tmpIndexItem[2] = strArr.length - 1;
        tmpIndexList.add(tmpIndexItem);

        // and remove first temporary empty entry
        if (tmpIndexList != null && tmpIndexList.size() > 0) {
            tmpIndexList.remove(0);
        }

        return tmpIndexList;
    }

    /**
     * getDisplayListOnChange method display the list from the index.
     * @param displayScreen , specify which screen it belongs
     */
    public void getDisplayListOnChange() 
    {
        LinearLayout sideIndex = (LinearLayout) findViewById(R.id.sideIndex);
        sideIndexHeight = sideIndex.getHeight();
        
        if (sideIndexHeight == 0) {
            Display display = getWindowManager().getDefaultDisplay();
            sideIndexHeight = display.getHeight();
            // Navigation Bar + Tab space comes approximately 80dip
        }    
        sideIndex.removeAllViews();
        /**
         * temporary TextView for every visible item
         */
        TextView tmpTV = null;

        /**
         * we will create the index list
         */
        String[] strArr = new String[userVector.size()];

        int j = 0;
        for (Book user : userVector) {
            strArr[j++] = user.getTitle().substring(0, 1);
        }

        indexList = getListArrayIndex(strArr);

        /**
         * number of items in the index List
         */
        indexListSize = indexList.size();

        /**
         * maximal number of item, which could be displayed
         */
        int indexMaxSize = (int) Math.floor(sideIndexHeight / 25);

        int tmpIndexListSize = indexListSize;

//      /**
//       * handling that case when indexListSize > indexMaxSize, if true display
//       * the half of the side index otherwise full index.
//       */
//      while (tmpIndexListSize > indexMaxSize) {
//          tmpIndexListSize = tmpIndexListSize / 2;
//      }

        /**
         * computing delta (only a part of items will be displayed to save a
         * place, without compact
         */
        double delta = indexListSize / tmpIndexListSize;

        String tmpLetter = null;
        Object[] tmpIndexItem = null;

        for (double i = 1; i <= indexListSize; i = i + delta) 
        {
            tmpIndexItem = indexList.get((int) i - 1);
            tmpLetter = tmpIndexItem[0].toString();
            tmpTV = new TextView(this);
            tmpTV.setTextColor(Color.parseColor("#000000"));
            tmpTV.setText(tmpLetter);
            tmpTV.setGravity(Gravity.CENTER);
            LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT,
                    LayoutParams.WRAP_CONTENT, 1);
            tmpTV.setLayoutParams(params);
            sideIndex.addView(tmpTV);
        }

        sideIndex.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                sideIndexX = event.getX();
                sideIndexY = event.getY();
                System.out.println("sideIndexX=="+sideIndexX);
                System.out.println("sideIndexY=="+sideIndexY);
                displayListItem();

                return false;
            }
        });
    }

    protected OnClickListener onClicked = new OnClickListener() {
        
        @Override
        public void onClick(View v) {
        }
    };
}
===============================================
Second java file named IndexTableActivity.java

package com.index.table;

import java.util.Vector;

import android.os.Bundle;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.index.table.service.UserService;
import com.index.table.to.Book;

public class IndexTableActivity extends CustomListIndex
{
    private ListView booksLV;
   
    private UserListAdapter userListAdapter;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        booksLV = (ListView)findViewById(R.id.booksLV);
       
        userVector = UserService.getUserList();
       
        Vector<Book> subsidiesList = getIndexedBooks(userVector);
        totalListSize = subsidiesList.size();
       
        userListAdapter = new UserListAdapter(this, subsidiesList);
        booksLV.setAdapter(userListAdapter);
       
        LinearLayout sideIndex = (LinearLayout) findViewById(R.id.sideIndex);
        sideIndex.setOnClickListener(onClicked);
        sideIndexHeight = sideIndex.getHeight();
        mGestureDetector = new GestureDetector(this,
                new ListIndexGestureListener());
    }
   
    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);

        getDisplayListOnChange();
    }
   
   
    private Vector<Book> getIndexedBooks(
            Vector<Book> booksVector) {
       
        //Retrieve it from DB in shorting order
       
        Vector<Book> v = new Vector<Book>();
        //Add default item
     
        String idx1 = null;
        String idx2 = null;
        for (int i = 0; i < booksVector.size(); i++) {
            Book temp = booksVector.elementAt(i);
            //Insert the alphabets
            idx1 = (temp.getTitle().substring(0, 1)).toLowerCase();
            if(!idx1.equalsIgnoreCase(idx2))
            {
                v.add(new Book(idx1.toUpperCase(), "", "" , "" , ""));
                idx2 = idx1;
                dealList.add(i);
            }
            v.add(temp);
        }      
        return v;
    }
   
    /**
     * ListIndexGestureListener method gets the list on scroll.
     */
    private class ListIndexGestureListener extends
            GestureDetector.SimpleOnGestureListener {
        @Override
        public boolean onScroll(MotionEvent e1, MotionEvent e2,
                float distanceX, float distanceY) {
            /**
             * we know already coordinates of first touch we know as well a
             * scroll distance
             */
            sideIndexX = sideIndexX - distanceX;
            sideIndexY = sideIndexY - distanceY;

            /**
             * when the user scrolls within our side index, we can show for
             * every position in it a proper item in the list
             */
            if (sideIndexX >= 0 && sideIndexY >= 0) {
                displayListItem();
            }
            return super.onScroll(e1, e2, distanceX, distanceY);
        }
    }
}
===============================================

Third java file named UserListAdapter.java
package com.index.table;

import java.util.Vector;

import android.app.Activity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.index.table.to.Book;

public class UserListAdapter extends BaseAdapter {

    private static final String TAG = UserListAdapter.class.getName();
    private Activity activity;
    private Vector<Book> items;
   
    public UserListAdapter(Activity activity,
            Vector<Book> items) {
        Log.i(TAG, TAG);
        this.activity = activity;
        this.items = items;
    }
    public View getView(final int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
           
            LayoutInflater inflater = activity.getLayoutInflater();
            convertView = inflater.inflate(R.layout.listrow_user, null);
            holder = new ViewHolder();

            holder.name = (TextView) convertView.findViewById(R.id.nameTV);
            holder.headingLL = (LinearLayout)convertView.findViewById(R.id.headingLL);
            holder.headingTV = (TextView)convertView.findViewById(R.id.headingTV);
            holder.nameLL = (LinearLayout)convertView.findViewById(R.id.nameLL);
            convertView.setTag(holder);

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

        if (position < items.size()) {

            final Book book = items.get(position);
            if (book != null
                    && (book.getTitle().length() == 1))
            {
                holder.nameLL.setVisibility(View.GONE);
                holder.headingLL.setVisibility(View.VISIBLE);
                holder.headingTV.setText(book.getTitle());
                holder.headingLL.setBackgroundColor(android.R.color.black);
            }
            else
            {
                holder.nameLL.setVisibility(View.VISIBLE);
                holder.headingLL.setVisibility(View.GONE);
                holder.name.setText(book.getTitle());
               
                View ll = (LinearLayout)holder.name.getParent();
                ll.setFocusable(true);
                ll.setSelected(true);
                ll.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Toast.makeText(activity.getApplicationContext(), "Clicked on " + book.getTitle(), Toast.LENGTH_SHORT).show();
                    }
                });
            }
        }
        return convertView;
    }

    private static class ViewHolder {
        TextView name,headingTV;
        LinearLayout nameLL,headingLL;
    }

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

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

    @Override
    public long getItemId(int position) {
        return position;
    }
}
===========================================
Create new package and a file name UserService.java

package com.index.table.service;

import java.util.Collections;
import java.util.Vector;

import com.index.table.to.Book;

public class UserService {

    public static Vector<Book> getUserList() {
        Vector<Book> bookList = new Vector<Book>();

        Book book = new Book("Things Fall Apart ", "Chinua Achebe ", "1958", " Nigeria ", "English");
        bookList.add(book);
        book = new Book("Fairy tales ", "Hans Christian Andersen ", "183537 ", "Denmark ", "Danish");
        bookList.add(book);
        book = new Book("The Divine Comedy ", "Dante Alighieri ", "12651321 ", "Florence ", "Italian");
        bookList.add(book);
        book = new Book("Epic of Gilgamesh ", "Anonymous ", "18th  17th century BC ", "Sumer and Akkadian Empire ", "Akkadian");
        bookList.add(book);
        book = new Book("Book of Job ", "Anonymous ", "6th 4th century BC ", "Achaemenid Empire ", "Hebrew");
        bookList.add(book);
        book = new Book("One Thousand and One Nights ", "Anonymous ", "7001500 ", "India/Iran/Iraq/Egypt ", "Arabic");
        bookList.add(book);
        book = new Book("Nj�l's Saga ", "Anonymous ", "13th century ", "Iceland ", "Old Norse");
        bookList.add(book);
        book = new Book("Pride and Prejudice ", "Jane Austen ", "1813", " United Kingdom ", "English");
        bookList.add(book);
        book = new Book("Le P�re Goriot ", "Honor� de Balzac ", "1835", " France ", "French");
        bookList.add(book);
        book = new Book("Molloy, Malone Dies, The Unnamable, a trilogy ", "Samuel Beckett ", "1951�53 ", "Republic of Ireland ", "French, English");
        bookList.add(book);
        book = new Book("The Decameron ", "Giovanni Boccaccio ", "1349�53 ", "Ravenna ", "Italian");
        bookList.add(book);
        book = new Book("Ficciones ", "Jorge Luis Borges ", "1944�86 ", "Argentina ", "Spanish");
        bookList.add(book);
        book = new Book("Wuthering Heights ", "Emily Bront� ", "1847", "  United Kingdom ", "English");
        bookList.add(book);
        book = new Book("The Stranger ", "Albert Camus ", "1942", "   Algeria, French Empire ", "French");
        bookList.add(book);
        book = new Book("Poems ", "Paul Celan ", "1952", "    Romania, France ", "German");
        bookList.add(book);
        book = new Book("Journey to the End of the Night ", "Louis-Ferdinand C�line ", "1932", "  France ", "French");
        bookList.add(book);
        book = new Book("Don Quixote ", "Miguel de Cervantes ", "1605 (part 1), 1615 (part 2) ", "Spain ", "Spanish");
        bookList.add(book);
        book = new Book("The Canterbury Tales ", "Geoffrey Chaucer ", "14th century ", "England ", "English");
        bookList.add(book);
        book = new Book("Stories ", "Anton Chekhov ", "1886", "   Russia ", "Russian");
        bookList.add(book);
        book = new Book("Nostromo ", "Joseph Conrad ", "1904", "  United Kingdom ", "English");
        bookList.add(book);
        book = new Book("Great Expectations ", "Charles Dickens ", "1861", "  United Kingdom ", "English");
        bookList.add(book);
        book = new Book("Jacques the Fatalist ", "Denis Diderot ", "1796", "  France ", "French");
        bookList.add(book);
        book = new Book("Berlin Alexanderplatz ", "Alfred D�blin ", "1929", " Germany ", "German");
        bookList.add(book);
        book = new Book("Crime and Punishment ", "Fyodor Dostoyevsky ", "1866", " Russia ", "Russian");
        bookList.add(book);
        book = new Book("The Idiot ", "Fyodor Dostoyevsky ", "1869", "    Russia ", "Russian");
        bookList.add(book);
        book = new Book("The Possessed ", "Fyodor Dostoyevsky ", "1872", "    Russia ", "Russian");
        bookList.add(book);
        book = new Book("The Brothers Karamazov ", "Fyodor Dostoyevsky ", "1880", "   Russia ", "Russian");
        bookList.add(book);
        book = new Book("Middlemarch ", "George Eliot ", "1871", "    United Kingdom ", "English");
        bookList.add(book);
        book = new Book("Invisible Man ", "Ralph Ellison ", "1952", " United States ", "English");
        bookList.add(book);
        book = new Book("Medea ", "Euripides ", "431 BC ", "Athens ", "Classical Greek");
        bookList.add(book);
        book = new Book("Absalom, Absalom! ", "William Faulkner ", "1936", "  United States ", "English");
        bookList.add(book);
        book = new Book("The Sound and the Fury ", "William Faulkner ", "1929", " United States ", "English");
        bookList.add(book);
        book = new Book("Madame Bovary ", "Gustave Flaubert ", "1857", "  France ", "French");
        bookList.add(book);
        book = new Book("Sentimental Education ", "Gustave Flaubert ", "1869", "  France ", "French");
        bookList.add(book);
        book = new Book("Gypsy Ballads ", "Federico Garc�a Lorca ", "1928", " Spain ", "Spanish");
        bookList.add(book);
        book = new Book("One Hundred Years of Solitude ", "Gabriel Garc�a M�rquez ", "1967", "    Colombia ", "Spanish");
        bookList.add(book);
        book = new Book("Love in the Time of Cholera ", "Gabriel Garc�a M�rquez ", "1985", "  Colombia ", "Spanish");
        bookList.add(book);
        book = new Book("Faust ", "Johann Wolfgang von Goethe ", "1832", "    Saxe-Weimar, Germany ", "German");
        bookList.add(book);
        book = new Book("Dead Souls ", "Nikolai Gogol ", "1842", "    Russia ", "Russian");
        bookList.add(book);
        book = new Book("The Tin Drum ", "G�nter Grass ", "1959", "   West Germany ", "German");
        bookList.add(book);
        book = new Book("The Devil to Pay in the Backlands ", "Jo�o Guimar�es Rosa ", "1956", "   Brazil ", "Portuguese");
        bookList.add(book);
        book = new Book("Hunger ", "Knut Hamsun ", "1890", "  Norway ", "Norwegian");
        bookList.add(book);
        book = new Book("The Old Man and the Sea ", "Ernest Hemingway ", "1952", "    United States ", "English");
        bookList.add(book);
        book = new Book("Iliad ", "Homer ", "850�750 BC ", "Possibly Smyrna ", "Classical Greek");
        bookList.add(book);
        book = new Book("Odyssey ", "Homer ", "8th century BC ", "Possibly Smyrna ", "Classical Greek");
        bookList.add(book);
        book = new Book("A Doll's House ", "Henrik Ibsen ", "1879", " Norway ", "Norwegian");
        bookList.add(book);
        book = new Book("Ulysses ", "James Joyce ", "1922", " Irish Free State ", "English");
        bookList.add(book);
        book = new Book("Stories ", "Franz Kafka ", "1924", " Austria ", "German");
        bookList.add(book);
        book = new Book("The Trial ", "Franz Kafka ", "1925", "   Austria ", "German");
        bookList.add(book);
        book = new Book("The Castle ", "Franz Kafka ", "1926", "  Austria ", "German");
        bookList.add(book);
        book = new Book("Shakuntala ", "Kalidasa ", "1st century BC � 4th century AD ", "India ", "Sanskrit");
        bookList.add(book);
        book = new Book("The Sound of the Mountain ", "Yasunari Kawabata ", "1954", " Japan ", "Japanese");
        bookList.add(book);
        book = new Book("Zorba the Greek ", "Nikos Kazantzakis ", "1946", "   Greece ", "Greek");
        bookList.add(book);
        book = new Book("Sons and Lovers ", "D. H. Lawrence ", "1913", "  United Kingdom ", "English");
        bookList.add(book);
        book = new Book("Independent People ", "Halld�r Laxness ", "1934�35 ", "Iceland ", "Icelandic");
        bookList.add(book);
        book = new Book("Poems ", "Giacomo Leopardi ", "1818", "  Italy ", "Italian");
        bookList.add(book);
        book = new Book("The Golden Notebook ", "Doris Lessing ", "1962", "   United Kingdom ", "English");
        bookList.add(book);
        book = new Book("Pippi Longstocking ", "Astrid Lindgren ", "1945", "  Sweden ", "Swedish");
        bookList.add(book);
        book = new Book("A Madman's Diary ", "Lu Xun ", "1918", " China ", "Chinese");
        bookList.add(book);
        book = new Book("Children of Gebelawi ", "Naguib Mahfouz ", "1959", " Egypt ", "Arabic");
        bookList.add(book);
        book = new Book("Buddenbrooks ", "Thomas Mann ", "1901", "    Germany ", "German");
        bookList.add(book);
        book = new Book("The Magic Mountain ", "Thomas Mann ", "1924", "  Germany ", "German");
        bookList.add(book);
        book = new Book("Moby-Dick ", "Herman Melville ", "1851", "   United States ", "English");
        bookList.add(book);
        book = new Book("Essays ", "Michel de Montaigne ", "1595", "  France ", "French");
        bookList.add(book);
        book = new Book("History ", "Elsa Morante ", "1974", "    Italy ", "Italian");
        bookList.add(book);
        book = new Book("Beloved ", "Toni Morrison ", "1987", "   United States ", "English");
        bookList.add(book);
        book = new Book("The Tale of Genji ", "Murasaki Shikibu ", "11th century ", "Japan ", "Japanese");
        bookList.add(book);
        book = new Book("The Man Without Qualities ", "Robert Musil ", "1930�32 ", "Austria ", "German");
        bookList.add(book);
        book = new Book("Lolita ", "Vladimir Nabokov ", "1955", " Russia/United States ", "English");
        bookList.add(book);
        book = new Book("Nineteen Eighty-Four ", "George Orwell ", "1949", "  United Kingdom ", "English");
        bookList.add(book);
        book = new Book("Metamorphoses ", "Ovid ", "1st century AD ", "Roman Empire ", "Classical Latin");
        bookList.add(book);
        book = new Book("The Book of Disquiet ", "Fernando Pessoa ", "1928", "    Portugal ", "Portuguese");
        bookList.add(book);
        book = new Book("Tales ", "Edgar Allan Poe ", "19th century ", "United States ", "English");
        bookList.add(book);
        book = new Book("In Search of Lost Time ", "Marcel Proust ", "1913�27 ", "France ", "French");
        bookList.add(book);
        book = new Book("The Life of Gargantua and of Pantagruel ", "Fran�ois Rabelais ", "1532�34 ", "France ", "French");
        bookList.add(book);
        book = new Book("Pedro P�ramo ", "Juan Rulfo ", "1955", " Mexico ", "Spanish");
        bookList.add(book);
        book = new Book("Masnavi ", "Rumi ", "1258�73 ", "Persia, Mongol Empire ", "Persian");
        bookList.add(book);
        book = new Book("Midnight's Children ", "Salman Rushdie ", "1981", "  United Kingdom ", "English");
        bookList.add(book);
        book = new Book("Bostan ", "Saadi ", "1257", "    Persia, Mongol Empire ", "Persian");
        bookList.add(book);
        book = new Book("Season of Migration to the North ", "Tayeb Salih ", "1971", "    Sudan ", "Arabic");
        bookList.add(book);
        book = new Book("Blindness ", "Jos� Saramago ", "1995", " Portugal ", "Portuguese");
        bookList.add(book);
        book = new Book("Hamlet ", "William Shakespeare ", "1603", "  England ", "English");
        bookList.add(book);
        book = new Book("King Lear ", "William Shakespeare ", "1608", "   England ", "English");
        bookList.add(book);
        book = new Book("Othello ", "William Shakespeare ", "1609", " England ", "English");
        bookList.add(book);
        book = new Book("Oedipus the King ", "Sophocles ", "430 BC ", "Athens ", "Classical Greek");
        bookList.add(book);
        book = new Book("The Red and the Black ", "Stendhal ", "1830", "  France ", "French");
        bookList.add(book);
        book = new Book("Tristram Shandy ", "Laurence Sterne ", "1760", " England ", "English");
        bookList.add(book);
        book = new Book("Confessions of Zeno ", "Italo Svevo ", "1923", " Italy ", "Italian");
        bookList.add(book);
        book = new Book("Gulliver's Travels ", "Jonathan Swift ", "1726", "   Ireland ", "English");
        bookList.add(book);
        book = new Book("War and Peace ", "Leo Tolstoy ", "1865�1869 ", "Russia ", "Russian");
        bookList.add(book);
        book = new Book("Anna Karenina ", "Leo Tolstoy ", "1877", "   Russia ", "Russian");
        bookList.add(book);
        book = new Book("The Death of Ivan Ilyich ", "Leo Tolstoy ", "1886", "    Russia ", "Russian");
        bookList.add(book);
        book = new Book("Adventures of Huckleberry Finn ", "Mark Twain ", "1884", "   United States ", "English");
        bookList.add(book);
        book = new Book("Ramayana ", "Valmiki ", "3rd century BC � 3rd century AD ", "India ", "Sanskrit");
        bookList.add(book);
        book = new Book("Aeneid ", "Virgil ", "29�19 BC ", "Roman Empire ", "Classical Latin");
        bookList.add(book);
        book = new Book("Mahabharata ", "Vyasa ", "4th century BC � 4th century AD ", "India ", "Sanskrit");
        bookList.add(book);
        book = new Book("Leaves of Grass ", "Walt Whitman ", "1855", "    United States ", "English");
        bookList.add(book);
        book = new Book("Mrs Dalloway ", "Virginia Woolf ", "1925", " United Kingdom ", "English");
        bookList.add(book);
        book = new Book("To the Lighthouse ", "Virginia Woolf ", "1927", "    United Kingdom ", "English");
        bookList.add(book);
        book = new Book("Memoirs of Hadrian ", "Marguerite Yourcenar ", "1951", " France ", "French");
        bookList.add(book);
        Collections.sort(bookList);
        return bookList;
    }

}
===========================================
create third packeage and add a file named Book.java

package com.index.table.to;

public class Book implements Comparable<Book>
{   
    private String title;
   
    private String author;
   
    private String year;
   
    private String country;
   
    private String language;

    public Book() {
        // TODO Auto-generated constructor stub
    }
   
    public Book(String title, String author, String year, String country, String language) {
        super();
        this.title = title;
        this.author = author;
        this.year = year;
        this.country = country;
        this.language = language;
    }

    /**
     * @return the title
     */
    public String getTitle() {
        return title;
    }

    /**
     * @param title the title to set
     */
    public void setTitle(String title) {
        this.title = title;
    }

    /**
     * @return the author
     */
    public String getAuthor() {
        return author;
    }

    /**
     * @param author the author to set
     */
    public void setAuthor(String author) {
        this.author = author;
    }

    /**
     * @return the year
     */
    public String getYear() {
        return year;
    }

    /**
     * @param year the year to set
     */
    public void setYear(String year) {
        this.year = year;
    }

    /**
     * @return the country
     */
    public String getCountry() {
        return country;
    }

    /**
     * @param country the country to set
     */
    public void setCountry(String country) {
        this.country = country;
    }

    /**
     * @return the language
     */
    public String getLanguage() {
        return language;
    }

    /**
     * @param language the language to set
     */
    public void setLanguage(String language) {
        this.language = language;
    }

    @Override
    public int compareTo(Book book) {
        return this.getTitle().compareTo(book.getTitle());
    }
}
=========================================

create xml named listrow_user.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/listitem_test"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:clickable="true"
    android:focusable="true"
    android:gravity="center_vertical"
    android:orientation="vertical" >
    <LinearLayout
        android:id="@+id/nameLL"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="@color/white"
        android:clickable="true"
        android:focusable="true"
        android:orientation="horizontal" >
        <TextView
            android:id="@+id/nameTV"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#000000"
            android:layout_marginTop="5dip"
            android:layout_marginRight="5dip"
            android:padding="10dip"
            android:textSize="14dip"
            android:text="@+id/TextView01" >
        </TextView>
    </LinearLayout>
    <LinearLayout
        android:id="@+id/headingLL"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/black" >
        <TextView
            android:id="@+id/headingTV"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="16dip"
            android:paddingLeft="10dip"
            android:textColor="@color/black"
            android:text="@+id/TextView01" >
        </TextView>
    </LinearLayout>
</LinearLayout>
================================================
create second xml named main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="#acacb7"
        android:orientation="horizontal" >

        <ListView
            android:id="@+id/booksLV"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:cacheColorHint="#00000000"
            android:divider="@color/gray"
            android:dividerHeight="1px" >
        </ListView>

        <LinearLayout
            android:id="@+id/sideIndex"
            android:layout_width="20dip"
            android:layout_height="fill_parent"
            android:background="@android:color/white"
            android:gravity="center_horizontal"
            android:orientation="vertical" >
        </LinearLayout>
    </LinearLayout>   

</LinearLayout>

========================================
in manifest.xml add

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.index.table"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk android:minSdkVersion="8" />
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:label="@string/app_name"
            android:name=".IndexTableActivity" >
            <intent-filter >
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

No comments:

Post a Comment