First create a class derived from LinearLayout
or RelativeLayout
that implements interface Checkable
Example for LinearLayout
public class CheckableLinearLayout extends LinearLayout implements Checkable{
private boolean checked = false;
private static final int[] CHECKED_STATE_SET = { android.R.attr.state_checked };
public CheckableLinearLayout(Context context) {
super(context);
}
public CheckableLinearLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
// Requer API level 11
/* public CheckableLinearLayout(Context context, AttributeSet attrs,
int defStyle) {
super(context, attrs, defStyle);
}*/
@Override
protected int[] onCreateDrawableState(int extraSpace) {
final int[] drawableState = super.onCreateDrawableState(extraSpace + 1);
if (isChecked())
mergeDrawableStates(drawableState, CHECKED_STATE_SET);
return drawableState;
}
@Override
public boolean isChecked(){
return checked;
}
@Override
public void setChecked(boolean checked) {
this.checked = checked;
refreshDrawableState();
}
@Override
public void toggle() {
setChecked(!checked);
}
}
You should then use this Layout to define the layout of the items on your list:
list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<yourPackage.CheckableLinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/listItemLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/lbId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</yourPackage.CheckableLinearLayout>
In the data associated with the list you must have a boolean
flag that will indicate whether it is selected or not.
No Adapter
check the flag and make listItemLayout.setChecked(false)
or listItemLayout.setChecked(true);
according to the flag.
In the onClick associated with the list you should put the flag with true
.