Читая исходный код simple_list_item_single_choice.xml , мы можем выяснить, как создать собственный виджет, который реализует Checkable , например:
File simple_list_item_2_single_choice.xml
<?xml version="1.0" encoding="utf-8"?>
<customwidgets.CheckedLinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal"
android:paddingBottom="10dp"
android:paddingTop="10dp" >
<TextView
android:id="@+id/text2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:textAppearance="?android:attr/textAppearanceMedium" />
<CheckedTextView
android:id="@+id/text3"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:textAppearance="?android:attr/textAppearanceMedium"
android:checkMark="?android:attr/listChoiceIndicatorSingle" />
</customwidgets.CheckedLinearLayout>
То есть, мы добавляем столько TextView
s, сколько нам нужно, и делаем последним равным CheckedTextView
.
Затем в нашем пользовательском CheckedLinearLayout
мынайдите, какой из них является Checkable
дочерним элементом макета, и отправьте каждый метод Checkable
, который мы реализуем этому дочернему элементу, например:
File CheckedLinearLayout.java
package customwidgets;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.Checkable;
import android.widget.LinearLayout;
/**
* Useful class inside a ListView that needs to have checkable items,
* such as radio buttons (single_choice) or check boxes (multiple_choice).
*/
public class CheckedLinearLayout extends LinearLayout implements Checkable {
private Checkable checkedView;
public CheckedLinearLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean isChecked() {
return checkedView == null ? false : checkedView.isChecked();
}
@Override
public void setChecked(boolean checked) {
if (checkedView != null) checkedView.setChecked(checked);
}
@Override
public void toggle() {
if (checkedView != null) checkedView.toggle();
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
int count = getChildCount();
for (int i = count - 1; i >= 0; i--) {
View view = getChildAt(i);
if (view instanceof Checkable) {
checkedView = (Checkable) view;
break;
}
}
}
}
Конечнов желаемом xml-файле макета мы устанавливаем ListView
на один выбор:
<ListView
android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:choiceMode="singleChoice" >
</ListView>