1

I have a custom listview with two textviews . If I use the emulator d-pad, everything works fine, the row is selected, but if I click on the item on the emulator (or try to select on the phone) nothing get selected.

addresslist.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="wrap_content"
    android:orientation="horizontal" android:paddingBottom="6dip"
    android:paddingTop="4dip">

    <TextView android:id="@+id/DENUMIRE_CELL"
        android:layout_width="50dp" android:layout_height="wrap_content"
        android:layout_weight="1.03" />

    <TextView android:id="@+id/ADRESA_CELL" android:layout_width="50dp"
        android:layout_height="wrap_content" android:layout_weight="0.84" />
</LinearLayout>
clienti.xml:

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

    <TableRow android:id="@+id/tableRow1" android:layout_width="fill_parent"
        android:layout_height="wrap_content">

        <LinearLayout android:orientation="horizontal"
            android:focusable="true" android:focusableInTouchMode="true">
            <EditText android:id="@+id/editTextCauta"
                android:layout_width="100dp" android:layout_height="wrap_content"
                android:layout_weight="0.04" />

            <Button android:id="@+id/buttonCauta" android:layout_width="70dp"
                android:layout_height="wrap_content" android:text="Cauta" />
        </LinearLayout>

    </TableRow>
    <TableRow android:id="@+id/tableRowHeader"
        android:layout_width="fill_parent" android:layout_height="wrap_content"
        android:background="#000000">

        <LinearLayout android:orientation="horizontal">
            <TextView android:id="@+id/textView1" android:layout_width="159dp"
                android:layout_height="wrap_content" android:text="Denumire"
                android:textAppearance="?android:attr/textAppearanceLarge"
                android:textColor="#BBBBBB" android:textSize="15sp" />
            <TextView android:id="@+id/textView2" android:layout_width="159dp"
                android:layout_height="wrap_content" android:text="Adresa"
                android:textAppearance="?android:attr/textAppearanceLarge"
                android:textColor="#BBBBBB" android:textSize="15sp" />

        </LinearLayout>

    </TableRow>
    <TableRow android:id="@+id/tableRow2" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:baselineAligned="false">


        <ListView android:id="@+id/adresslist" android:layout_width="wrap_content"
            android:choiceMode="singleChoice" android:layout_height="wrap_content"
            android:scrollbars="horizontal|vertical" />

    </TableRow>


</TableLayout>

Code:

    public void adresalistBind()
        {
            listview = (ListView) findViewById(R.id.adresslist);

            ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
            ArrayList<ClientClass> clientlist=new ArrayList<ClientClass>();

            ClientClass.setClientContextForDB(this);

            clientlist=ClientClass.ClientiGet();

            listaAll=clientlist;


            HashMap<String, String> map;

            for(int i=0;i<clientlist.size();i++)
            {
                map = new HashMap<String, String>();
                map.put("denumire", clientlist.get(i).getDenumire());
                map.put("adresa", clientlist.get(i).getAdresa());
                map.put("clientid", String.valueOf(clientlist.get(i).getClientID()));
                mylist.add(map);
            }

            SimpleAdapter mAdapter = new SimpleAdapter(this, mylist, R.layout.addresslist,
                        new String[] {"denumire", "adresa"}, new int[] {R.id.DENUMIRE_CELL, R.id.ADRESA_CELL});
            listview.setAdapter(mAdapter);
            listview.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
            listview.setSelection(1);
            listview.setOnItemSelectedListener(new OnItemSelectedListener() 
            {
                public void onItemSelected(AdapterView<?> adaptview, View clickedview, int position,
                        long id) 
                {
                    //adaptview.setSelected(true);
                    listview.setSelection(position);
                }

                public void onNothingSelected(AdapterView<?> arg0) 
                {
                }

            });

            listview.setOnItemClickListener(new OnItemClickListener() 
            {
                public void onItemClick(AdapterView<?> adaptview, View arg1,
                        int position, long arg3) 
                {
                    //adaptview.setSelected(true);
                   // View rowview = (View) adaptview.getChildAt(position);
                   // rowview.setSelected(true);
                    listview.setSelection(position);

                    //Toast.makeText(ClientiForm.this,  (String) listview.getItemAtPosition(position).toString(), 10000).show();
                }
            });

            listview.setOnItemLongClickListener(new OnItemLongClickListener() 
            {

                public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                        int position, long arg3) 
                {
                    listview.setSelection(position);
                    openOptionsMenu();

                    Toast.makeText(ClientiForm.this,  (String) listview.getItemAtPosition(position).toString(), 10000).show();
                    return false;
                }
            });
        }
Jonas
  • 121,568
  • 97
  • 310
  • 388

1 Answers1

6

In order for item to be "checkable", the top view of the item should implement Checkable interface. Only in this case you'll get "checked"/"unchecked" states within ListView.

Note that "selectable" and "checkable" items have different meanings. In your case you mean "checkable" item. Not "selectable". You need your items to be "checked", but ListView makes sure there is at most one item checked at a time in CHOICE_MODE_SINGLE. While "selected" item is item that is currently active (this is mostly used for accessibility needs).

You can verify what I said by simply replacing LinearLayout with CheckBox view in your list item's layout. And ListView should start handling "checked" states automatically.


If you want to use LinearLayout and still be able to support "checked"/"unchecked" states, you need to implement custom layout that extends LinearLayout and implements Checkable interface.

Here is what my version of this implementation is:

public class CheckableLinearLayout extends LinearLayout implements Checkable {

    private boolean mChecked;

    private static final int[] CHECKED_STATE_SET = {
        android.R.attr.state_checked
    };

    public CheckableLinearLayout(Context context) {
        this(context, null);
        init();
    }

    public CheckableLinearLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {      
        setClickable(true);
    }

    /**********************/
    /**   Handle clicks  **/
    /**********************/

    @Override
    public boolean performClick() {
        toggle();
        return super.performClick();
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        return onTouchEvent(ev);
    }

    /**************************/
    /**      Checkable       **/
    /**************************/

    public void toggle() {
        setChecked(!mChecked);
    }

    public boolean isChecked() {
        return mChecked;
    }

    public void setChecked(boolean checked) {
        if (mChecked != checked) {
            mChecked = checked;
            refreshDrawableState();
            setCheckedRecursive(this, checked);
        }
    }  

    private void setCheckedRecursive(ViewGroup parent, boolean checked) {
        int count = parent.getChildCount();
        for(int i = 0; i < count; i++ ) { 
            View v = parent.getChildAt(i);
            if(v instanceof Checkable) {
                ((Checkable) v).setChecked(checked);
            }

            if(v instanceof ViewGroup) {
                setCheckedRecursive((ViewGroup)v, checked);
            }
        }
    }

    /**************************/
    /**   Drawable States    **/
    /**************************/

    @Override
    protected int[] onCreateDrawableState(int extraSpace) {
        final int[] drawableState = super.onCreateDrawableState(extraSpace + 1);
        if (isChecked()) {
            mergeDrawableStates(drawableState, CHECKED_STATE_SET);
        }
        return drawableState;
    }

    @Override
    protected void drawableStateChanged() {
        super.drawableStateChanged();

        Drawable drawable = getBackground();
        if (drawable != null) {
            int[] myDrawableState = getDrawableState();
            drawable.setState(myDrawableState);
            invalidate();
        }
    }

    /**************************/
    /**   State persistency  **/
    /**************************/

    static class SavedState extends BaseSavedState {
        boolean checked;

        SavedState(Parcelable superState) {
            super(superState);
        }

        private SavedState(Parcel in) {
            super(in);
            checked = (Boolean)in.readValue(null);
        }

        @Override
        public void writeToParcel(Parcel out, int flags) {
            super.writeToParcel(out, flags);
            out.writeValue(checked);
        }

        @Override
        public String toString() {
            return "CheckableLinearLayout.SavedState{"
                    + Integer.toHexString(System.identityHashCode(this))
                    + " checked=" + checked + "}";
        }

        public static final Parcelable.Creator<SavedState> CREATOR
                = new Parcelable.Creator<SavedState>() {
            public SavedState createFromParcel(Parcel in) {
                return new SavedState(in);
            }

            public SavedState[] newArray(int size) {
                return new SavedState[size];
            }
        };
    }

    @Override
    public Parcelable onSaveInstanceState() {
        // Force our ancestor class to save its state
        Parcelable superState = super.onSaveInstanceState();
        SavedState ss = new SavedState(superState);

        ss.checked = isChecked();
        return ss;
    }

    @Override
    public void onRestoreInstanceState(Parcelable state) {
        SavedState ss = (SavedState) state;

        super.onRestoreInstanceState(ss.getSuperState());
        setChecked(ss.checked);
        requestLayout();
    }
}

Your item layout should look something like:

<com.your.pkg.CheckableLinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/linearLayout1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" 
    android:background="@drawable/checkable_item">

        <TextView
            android:id="@+id/name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Large Text"
            android:textAppearance="?android:attr/textAppearanceLarge" />
</com.your.pkg.CheckableLinearLayout>

And note that "drawable/checakble_item". It should handle different states. In my example it looks like:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >

    <item android:state_pressed="true" android:drawable="@drawable/item_pressed" />
    <item android:state_checked="true" android:drawable="@drawable/item_checked"/>
    <item android:drawable="@drawable/item_unchecked" />

</selector>

Where drawable/item_pressed, drawable/item_checked and drawable/item_unchecked are my custom drawables.

The last note: in your Adapter's getView() you'll have to call view.setClickable(false); for checkable states to be handled by ListView and not by CheckableLinearLayout.

inazaruk
  • 74,247
  • 24
  • 188
  • 156
  • your code is working, but it checks multiple items, i want to check just one at a time. i tried to retrive the currently check item, but it's not working this way: if(listaAll.size()>0) { if(listview.getCheckedItemPosition()>=0) { Clientid=listaAll.get(listview.getCheckedItemPosition()).getClientID(); startActivity(new Intent(ClientiForm.this,ClientiDetaliiForm.class)); } else { Toast.makeText(ClientiForm.this,"Alegeti un client!", 10000).show(); } } – Stephan Miller Dec 11 '11 at 12:10
  • Make sure you've added `view.setClickable(false)` in your adapter's `getView()`. Or remove `setClickable(true)` from `CheckableLinearLayout`. – inazaruk Dec 11 '11 at 12:22
  • i added android:clickable="false" to CheckableLinearLayout in the addresslist.xml, but it checks multiple items – Stephan Miller Dec 11 '11 at 12:36
  • Xml's attribute is overriden by my implementation(see `init()`). You should do one of two things I mentioned. – inazaruk Dec 11 '11 at 14:28