3

I have a listview that populates the data from the cursor. The listview has a customadapter. I want to highlight the selected item in the listview

public class BillOfSaleActivity extends Activity {

    ListView lv1;
    CustomAdapter listAdapter;

    DbHandler dbHandler;
    Cursor c;

    TextView salesman;
    TextView customer;
    TextView TC;

    String userName;
    String custName;

    Float TotalCost = 0f;


    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bos_main);

        Intent i = getIntent();
        userName = i.getStringExtra("userName");
        custName = i.getStringExtra("custName");

        salesman = (TextView) findViewById(R.id.tv_bosSalesman);
        customer = (TextView) findViewById(R.id.tv_boscust);
        TC = (TextView) findViewById(R.id.textView_bos_total);

        salesman.setText(userName);
        customer.setText(custName);

        dbHandler = new DbHandler(getApplicationContext());
        c = dbHandler.getBosList();

        if (c != null) {
            if (c.moveToFirst())
                do {
                    Float qty = Float.parseFloat(c.getString(4));
                    Float price = Float.parseFloat(c.getString(5)) * qty;
                    TotalCost = TotalCost + price;
                } while (c.moveToNext());
        }

        c.moveToFirst();
        lv1 = (ListView) findViewById(R.id.listView_bos);
        lv1.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        lv1.setSelector(R.drawable.list_selector);

        // String []from = new String []
        // {DbHandler.Bos_List_col5,DbHandler.Bos_List_col6};
        listAdapter = new CustomAdapter(getApplicationContext(), c);
        lv1.setAdapter(listAdapter);

        TC.setText("$" + TotalCost);

        lv1.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View view, int position,
                    long arg3) {
                view.getFocusables(position);               
                view.setSelected(true);                 
            }
        });
    }

    public class CustomAdapter extends BaseAdapter {
        Cursor cursor;
        Context context;

        public CustomAdapter(Context cont, Cursor c) {

            this.cursor = c;
            this.context = cont;
        }

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return c.getCount();
        }

        @Override
        public Object getItem(int arg0) {
            // TODO Auto-generated method stub
            return arg0;
        }

        @Override
        public long getItemId(int arg0) {
            // TODO Auto-generated method stub
            return arg0;
        }

        @Override
        public View getView(int position, View view, ViewGroup arg2) {

            Log.i("dhiraj", "In getView");

            LayoutInflater inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = inflater.inflate(R.layout.activity_bos_list, null);

            cursor.moveToPosition(position);

            TextView textView1 = (TextView) view
                    .findViewById(R.id.textView1_bos);
            TextView textView2 = (TextView) view
                    .findViewById(R.id.textView2_bos);
            TextView textView3 = (TextView) view
                    .findViewById(R.id.textView3_bos);
            TextView textView4 = (TextView) view
                    .findViewById(R.id.textView4_bos);

            textView1.setText(cursor.getString(3));
            textView2.setText(cursor.getString(2));
            textView3.setText(cursor.getString(4) + " x  $"
                    + cursor.getString(5));

            Float qty = Float.parseFloat(cursor.getString(4));
            Float price = Float.parseFloat(cursor.getString(5)) * qty;

            textView4.setText("$ " + price);

            return view;
        }

    }
}

The layout I use is... this is the main layout.

<?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" >

    <LinearLayout
        android:id="@+id/linz"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:weightSum="2" >

        <TextView
            android:id="@+id/tv_bosSalesman"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:paddingLeft="20dp"
            android:text="Salesman"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:textColor="@color/red" />

        <TextView
            android:id="@+id/tv_boscust"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center"
            android:text="Customer"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:textColor="@color/lightBlue" />
    </LinearLayout>

    <TextView
        android:id="@+id/tv_bos_header"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/linz"
        android:background="@android:color/darker_gray"
        android:gravity="center"
        android:text="Nota de Venta"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <LinearLayout
        android:id="@+id/lin"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/tv_bos_header"
        android:weightSum="4" >

        <TextView
            android:id="@+id/textView1"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center"
            android:text="Cant"
            android:textAppearance="?android:attr/textAppearanceSmall" />

        <TextView
            android:id="@+id/textView2"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center"
            android:text="Cod"
            android:textAppearance="?android:attr/textAppearanceSmall" />

        <TextView
            android:id="@+id/textView3"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center"
            android:text="Nombre"
            android:textAppearance="?android:attr/textAppearanceSmall" />

        <TextView
            android:id="@+id/textView4"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center"
            android:text="Total"
            android:textAppearance="?android:attr/textAppearanceSmall" />
    </LinearLayout>

    <ListView
        android:id="@+id/listView_bos"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_above="@+id/linz12"
        android:layout_below="@+id/lin"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:dividerHeight="1dp"
        android:drawSelectorOnTop="true" />

    <LinearLayout
        android:id="@+id/linz234"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:weightSum="3" >

        <Button
            android:id="@+id/button_bos_eliminar"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Eliminar"
            android:textColorHint="@color/red" />

        <Button
            android:id="@+id/button_bos_agregar"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Agregar"
            android:textColorHint="@color/green" />

        <Button
            android:id="@+id/button_bos_finalizar"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Finalizar"
            android:textColorHint="@color/blue" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/linz12"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/linz234"
        android:layout_alignParentLeft="true"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/textView_bos_total"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="right"
            android:text="Large Text"
            android:textAppearance="?android:attr/textAppearanceLarge" />
    </LinearLayout>

</RelativeLayout>

The other layout contains 4 textboxes which is used for the Listview.

Now I want to highlight the pressed item in the Listview. How can I achieve that. I tried using the selector but no effect. I want that the item is highlighted till next item is selected .

Dhiraj Tayade
  • 407
  • 3
  • 10
  • 22
  • http://stackoverflow.com/questions/9281000/android-keep-listviews-item-highlighted-once-one-has-been-clicked?lq=1[enter link description here][1] [1]: http://stackoverflow.com/questions/9281000/android-keep-listviews-item-highlighted-once-one-has-been-clicked?lq=1 – Vishal Shah Mar 06 '15 at 12:53

4 Answers4

2

If u want to keep all selected items highlighted in the listview,

   **@Override
     public void onItemClick(AdapterView<?> adapterView, View view,
                    int position, long arg3) {
              view.setBackgroundColor(getResources().getColor(
                        R.color.pressed_color)); 
            //change the background color or image of the selected item
         }**
Rashid C Y
  • 121
  • 1
  • 6
  • 1
    And if you click another item? You'll have more items highlighted – Boldijar Paul Oct 06 '14 at 13:56
  • 1
    Of the dozens of answers across multiple threads on SO, this one - though incomplete - seems to be the most simple solution that actually works! I posted code below that adds to this so that items can be de-selected as well. Thanks for getting me going in the right direction – Gene Bo Mar 25 '15 at 18:41
0

ListViews by default don't have a choiceMode set, so the current selection is not indicated by default.

To change this, you just need to set the choiceMode attribute of your ListView to singleChoice. And to show selected items in your list, you should also set the listSelector attribute.

Example:

<ListView android:id="@+id/my_list"
        android:choiceMode="singleChoice" 
        android:listSelector="@android:color/darker_gray" />
user2511882
  • 9,022
  • 10
  • 51
  • 59
  • 1
    It just highlights the item for the time it is pressed. I want the behaviour that when I press and release it, the item should be highlighted continuously till other item is selected. When other item is pressed the highlight should be shifted from first to second – Dhiraj Tayade Dec 05 '13 at 17:16
  • Oh Ok. This link is what you are looking for. http://stackoverflow.com/questions/9281000/android-keep-listviews-item-highlighted-once-one-has-been-clicked.. And dont forget to accept and upvote if it worked for you. Cheers! – user2511882 Dec 05 '13 at 17:17
  • Thanks, But does anyone else have other options ? – Dhiraj Tayade Dec 05 '13 at 17:53
0

Continuing from Rashi's answer, here's the simple approach that worked for me - just keep track of the last selected item so you know which one to turn off from the previous click, before turning on the current selected item.

public class SomeActivity extends Activity {

    View previouslySelectedItem = null;

    ...
    protected void onCreate(Bundle savedInstanceState) {

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

        myListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                if (previouslySelectedItem != null)
                {
                    previouslySelectedItem.setBackgroundColor(
                            getResources().getColor(R.color.transparent));
                }

                view.setBackgroundColor(
                        getResources().getColor(R.color.orange));

                previouslySelectedItem = view;
            }
        });
Gene Bo
  • 11,284
  • 8
  • 90
  • 137
0

Take a look at this answer which helped me as well.

There you will find how to highlight an item in a listView and also keep it highlighted until another item is selected.

Community
  • 1
  • 1
P.Lorand
  • 1,394
  • 3
  • 17
  • 26