4

i have a names list and i want to change the color to the rows depending on the letter the name starts with. This is what i'm using to show the ListView:

main.xml

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

<ListView android:id="@+id/listview"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content" 
     />

</LinearLayout>

lisviewrows.xml

<?xml version="1.0" encoding="UTF-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
</TextView>

main.java

public class Main extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        List<String> words = populateList();
        List<String> l = removeDoubles(words);
        Collections.sort(l);

        ListView lv = (ListView)findViewById(R.id.listview);

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.listviewrows, l);

        lv.setAdapter(adapter);

        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

            }
        });
    }

Is there some useful link you can provide me with or some example?

Thanks!!

madcoderz
  • 4,423
  • 10
  • 47
  • 74

3 Answers3

14

To do so, you will need to create your own custom adapter. In the getView method (which returns the View to display for each list item), apply the color you want to your TextView's background. The cool thing about customAdapters is that you can do absolutely anything, and display much more complicated Views for your list items, because you are not restricted to TextViews anymore, you can change your list item XML layout to any kind of View/Layout...

Something like this:

MyAdapter.java

public class MyAdapter extends BaseAdapter{
    private LayoutInflater inflater;
    private ArrayList<String> data;

    public MyAdapter(Context context, ArrayList<String> data){
    // Caches the LayoutInflater for quicker use
    this.inflater = LayoutInflater.from(context);
    // Sets the events data
    this.data= data;
    }

    public int getCount() {
        return this.data.size();
    }

    public String getItem(int position) throws IndexOutOfBoundsException{
        return this.data.get(position);
    }

    public long getItemId(int position) throws IndexOutOfBoundsException{
        if(position < getCount() && position >= 0 ){
            return position;
        }
    }

    public int getViewTypeCount(){
        return 1;
    }

    public View getView(int position, View convertView, ViewGroup parent){
        String myText = getItem(position);           

        if(convertView == null){ // If the View is not cached
            // Inflates the Common View from XML file
            convertView = this.inflater.inflate(R.id.my_row_layout, null);
        }

        // Select your color and apply it to your textview
        int myColor;
        if(myText.substring(0, 1) == "a"){
            myColor = Color.BLACK;
        }else{
        ....
        }

        convertView.findViewById(R.id.myTextViewId).setBackground(myColor);
        // Of course you will need to set the same ID in your item list XML layout.

        return convertView;
    }
}

and then in your activity set the adapter like this:

public class Main extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        List<String> words = populateList();
        List<String> l = removeDoubles(words);
        Collections.sort(l);

        ListView lv = (ListView)findViewById(R.id.listview);

        MyAdapter adapter = new MyAdapter(getApplicationContext(), l);

        lv.setAdapter(adapter);

        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

            }
        });
    }
Houcine
  • 24,001
  • 13
  • 56
  • 83
nbarraille
  • 9,926
  • 14
  • 65
  • 92
  • I tried this but i get an air saying that i can't convert from Object to String in here: String myText = getItem(position); – madcoderz Dec 12 '10 at 10:22
  • Will this work if I have the list view and the item list controls in the same xml layout? And what's the reason for creating an item list xml layout file if you could just create the items on the activity? My guess is that it's more resourceful to create the object over and over? – Ben Sewards Mar 22 '13 at 02:20
2
    MainActivity:   

     import java.util.ArrayList;

        import android.app.Activity;
        import android.content.Intent;
        import android.content.SharedPreferences;
        import android.content.SharedPreferences.Editor;
        import android.os.Bundle;
        import android.view.View;
        import android.widget.Adapter;
        import android.widget.AdapterView;
        import android.widget.AdapterView.OnItemClickListener;
        import android.widget.ListView;

        public class ListViewImagesActivity extends Activity {
            ListView list;
            public Integer[] mgriArray = { R.drawable.angry0, R.drawable.neutral0,
                    R.drawable.fblack0, R.drawable.misc0, R.drawable.notok0,
                    R.drawable.panel011, R.drawable.pleasure0, R.drawable.rage0,
                    R.drawable.sad0, R.drawable.stupidity0, R.drawable.sa0,
                    R.drawable.tree0, R.drawable.victorious0,R.drawable.image_53,
                    R.drawable.image_13

            };
            ArrayList<ItemDetails> image_details;
            Adapter griAdapter;

            public static SharedPreferences pref;
            static Editor editor;

            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_main);

                 pref = getSharedPreferences("share", 0);
                  editor = pref.edit();
                list = (ListView) findViewById(R.id.listV_main);

                image_details = GetSearchResults3();
                list.setAdapter(new ItemListBaseAdapter(this, image_details, mgriArray));
                list.setOnItemClickListener(new OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View v,
                            int position, long id) {
                        Object o = list.getItemAtPosition(position);
                        ItemDetails obj_itemDetails = (ItemDetails) o;

                        String namee = obj_itemDetails.getName();
                          editor.putString("name", namee);

                            // commit changes
                            editor.commit();

                        // switch..................

                        switch (position) {
                        case 0:
                            Intent i1 = new Intent(ListViewImagesActivity.this,
                                    AndroidGridLayoutActivity.class);
                            startActivity(i1);
                            break;
                        case 1:
                            Intent i2 = new Intent(ListViewImagesActivity.this,
                                    AndroidGridLayoutActivity2.class);
                            startActivity(i2);
                            break;
                        case 2:
                            Intent i3 = new Intent(ListViewImagesActivity.this,
                                    AndroidGridLayoutActivity3.class);
                            startActivity(i3);
                            break;
                        case 3:
                            Intent i4 = new Intent(ListViewImagesActivity.this,
                                    AndroidGridLayoutActivity4.class);
                            startActivity(i4);
                            break;
                        case 4:
                            Intent i5 = new Intent(ListViewImagesActivity.this,
                                    AndroidGridLayoutActivity5.class);
                            startActivity(i5);
                            break;
                        case 5:
                            Intent i6 = new Intent(ListViewImagesActivity.this,
                                    AndroidGridLayoutActivity6.class);
                            startActivity(i6);
                            break;
                        case 6:
                            Intent i7 = new Intent(ListViewImagesActivity.this,
                                    AndroidGridLayoutActivity7.class);
                            startActivity(i7);
                            break;
                        case 7:
                            Intent i8 = new Intent(ListViewImagesActivity.this,
                                    AndroidGridLayoutActivity8.class);
                            startActivity(i8);
                            break;
                        case 8:
                            Intent i9 = new Intent(ListViewImagesActivity.this,
                                    AndroidGridLayoutActivity9.class);
                            startActivity(i9);
                            break;
                        case 9:
                            Intent i10 = new Intent(ListViewImagesActivity.this,
                                    AndroidGridLayoutActivity10.class);
                            startActivity(i10);
                            break;
                        case 10:
                            Intent i11 = new Intent(ListViewImagesActivity.this,
                                    AndroidGridLayoutActivity11.class);
                            startActivity(i11);
                            break;
                        case 11:
                            Intent i12 = new Intent(ListViewImagesActivity.this,
                                    AndroidGridLayoutActivity12.class);
                            startActivity(i12);
                            break;
                        case 12:
                            Intent i13 = new Intent(ListViewImagesActivity.this,
                                    AndroidGridLayoutActivity13.class);
                            startActivity(i13);
                            break;
                        case 13:
                            Intent i14 = new Intent(ListViewImagesActivity.this,
                                    AndroidGridLayoutActivity14.class);
                            startActivity(i14);
                            break;
                        case 14:
                            Intent i15 = new Intent(ListViewImagesActivity.this,
                                    AndroidGridLayoutActivity15.class);
                            startActivity(i15);
                            break;

                        }

                        // ending.........

                    }
                });
            }

            // ...............................

            public ArrayList<ItemDetails> GetSearchResults3() {
                // TODO Auto-generated method stub
                ArrayList<ItemDetails> results = new ArrayList<ItemDetails>();

                ItemDetails item_details = new ItemDetails();

                item_details.setName("ANGRY");
                item_details.setImageNumber(1);
                results.add(item_details);

                item_details = new ItemDetails();
                item_details.setName("NEUTRAL");
                item_details.setImageNumber(2);
                results.add(item_details);

                item_details = new ItemDetails();
                item_details.setName("FEMALE");
                item_details.setImageNumber(3);
                results.add(item_details);

                item_details = new ItemDetails();
                item_details.setName("MISC");
                item_details.setImageNumber(4);
                results.add(item_details);

                item_details = new ItemDetails();
                item_details.setName("NOTOK");
                item_details.setImageNumber(5);
                results.add(item_details);

                item_details = new ItemDetails();
                item_details.setName("PANEL");
                item_details.setImageNumber(6);
                results.add(item_details);

                item_details = new ItemDetails();
                item_details.setName("PLEASURE");
                item_details.setImageNumber(7);
                results.add(item_details);

                item_details = new ItemDetails();
                item_details.setName("RAGE");
                item_details.setImageNumber(8);
                results.add(item_details);

                item_details = new ItemDetails();
                item_details.setName("SAD");
                item_details.setImageNumber(9);
                results.add(item_details);

                item_details = new ItemDetails();
                item_details.setName("STUPIDITY");
                item_details.setImageNumber(10);
                results.add(item_details);

                item_details = new ItemDetails();
                item_details.setName("SURPRISED ");
                item_details.setImageNumber(11);
                results.add(item_details);

                item_details = new ItemDetails();
                item_details.setName("TREES");
                item_details.setImageNumber(12);
                results.add(item_details);

                item_details = new ItemDetails();
                item_details.setName("VICTORIOUS");
                item_details.setImageNumber(13);
                results.add(item_details);

                item_details = new ItemDetails();
                item_details.setName("LUCKY BEAR");
                item_details.setImageNumber(14);
                results.add(item_details);

                item_details = new ItemDetails();
                item_details.setName("LUCKY CHARM");
                item_details.setImageNumber(15);
                results.add(item_details);

                return results;
            }
        }



    Adapter Class...

    public class ItemListBaseAdapter extends BaseAdapter {
        private static ArrayList<ItemDetails> itemDetailsrrayList;
        private Integer[] imgid;

        public static ArrayList<ItemDetails> results;

        private LayoutInflater l_Inflater;

        public ItemListBaseAdapter(Context context, ArrayList<ItemDetails> results,
                Integer[] imgid) {
            itemDetailsrrayList = results;
            l_Inflater = LayoutInflater.from(context);
            this.imgid = imgid;
        }

        public int getCount() {
            return itemDetailsrrayList.size();
        }

        public Object getItem(int position) {
            return itemDetailsrrayList.get(position);
        }

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

        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            ImageView imageView = null;
            if (convertView == null) {
                convertView = l_Inflater.inflate(R.layout.category, null);
                holder = new ViewHolder();
                holder.txt_itemName = (TextView) convertView.findViewById(R.id.name);
                holder.itemImage = (ImageView) convertView.findViewById(R.id.photo);

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


            holder.txt_itemName.setText(itemDetailsrrayList.get(position).getName());
            holder.itemImage.setImageResource(imgid[itemDetailsrrayList.get(
                    position).getImageNumber() - 1]);


            return convertView;
        }

        static class ViewHolder {
            TextView txt_itemName;
            ImageView itemImage;

        }
    }   

XML ListView here......

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/rel1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#ffffff" >


    <RelativeLayout
        android:id="@+id/navi_b"
        android:layout_width="fill_parent"
        android:layout_height="65dp"
        android:layout_alignParentTop="true"
        android:background="@drawable/navigation" >

        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:textColor="#000000"
            android:text="Albums"
            android:textAppearance="?android:attr/textAppearanceLarge" />

    </RelativeLayout>

    <RelativeLayout
        android:id="@+id/navi_l"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_above="@+id/navigation1"
        android:layout_below="@+id/navi_b"
        android:background="@drawable/bg">"

        <ListView
            android:id="@+id/listV_main"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_below="@+id/navi_b"
            android:layout_above="@+id/navigation1"
            android:layout_alignParentBottom="true" >
        </ListView>
    </RelativeLayout>

    <RelativeLayout
        android:id="@+id/navigation1"
        android:layout_width="fill_parent"
        android:layout_height="60dp"
        android:layout_alignParentBottom="true"
        android:background="#ffffff" >

        <include
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_alignParentLeft="true"
            layout="@layout/tabb" />

    </RelativeLayout>

</RelativeLayout>
Balwinder Singh
  • 125
  • 1
  • 13
1

Your problem is that, you are sending as a parameter to the function setText, a number (int) and not a String. Hence, instead of:

holder.text2.setText(words.indexOf(position));

Try this:

holder.text2.setText("" + words.indexOf(position));

Good Luck!

Raz Tourgman
  • 567
  • 5
  • 9