在SingleChoice模式下使用RadioButton / CheckBox的Android ListView和自定义行布局

时间:2011-01-30 10:21:02

标签: android listview radio-button listviewitem

我有一个ListView,它处于singleChoice模式。我想要的只是在旁边显示一个RadioButton,当点击高亮显示它被选中时,当点击另一个时,隐藏一个并且新的被选中。

我查看了Mark的书,第8章,“用列表获得幻想”和他的RateList示例 但它并没有解决我的问题。 请帮帮我。

2 个答案:

答案 0 :(得分:13)

修改

值得一提的是我的列表项目上有自定义布局:有一个图标,一个标题,一个描述,然后是复选框或单选按钮(取决于它是单个还是多个选项列表)。我的示例解决方案是由不少于三个不同部分描述的:

  1. 自定义列表项目
  2. 甜蜜温柔的爱:CheckableLinearLayout实施
  3. 示例ListView配置

  4. 还有奖金:

  5. 示例Adapter::getView()实现。

那么,让我们接受魔术吧,是吗?

listitem.xml

<com.dbm.CheckableLinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <ImageView
        android:layout_width="32dp"
        android:layout_height="32dp"
        android:id="@+id/myIcon" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:orientation="vertical">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textAppearance="@android:style/TextAppearance.Medium"
            android:textStyle="bold"
            android:ellipsize="end"
            android:id="@+id/myTitle" />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textAppearance="@android:style/TextAppearance.Small"
            android:textStyle="italic"
            android:ellipsize="end"
            android:id="@+id/myDescr" />
    </LinearLayout>

    <CheckedTextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@android:id/text1" />

</com.dbm.CheckableLinearLayout>

CheckableLinearLayout.java

public class CheckableLinearLayout extends LinearLayout implements Checkable {

    private CheckedTextView mCheckedTextView;
    private final Drawable mCheckDrawable;
    private final Drawable mRadioDrawable;
    private boolean mIsChecked;


       /**
        * Constructor.
        *
        * @param context The context to operate in.
        * @param attrs The attributes defined in XML for this element.
        */
    public CheckableLinearLayout(Context context, AttributeSet attrs) {
        super(context, attrs);

        TypedArray typedArray = null;

        // Cache the check box drawable.
        typedArray = context.getTheme().obtainStyledAttributes(new int[] {android.R.attr.listChoiceIndicatorMultiple});

        if ((typedArray != null) && (typedArray.length() > 0)) {
            mCheckDrawable = typedArray.getDrawable(0);
        }
        else {
            // Fallback if the target theme doesn't define a check box drawable.
            // Perhaps an application specific drawable should be used instead of null.
            mCheckDrawable = null;
        }

        // Careful with resources like this, we don't need any memory leaks.
        typedArray.recycle();

        // Cache the radio button drawable.
        typedArray = context.getTheme().obtainStyledAttributes(new int[] {android.R.attr.listChoiceIndicatorSingle});

        if ((typedArray != null) && (typedArray.length() > 0)) {
            mRadioDrawable = typedArray.getDrawable(0);
        }
        else {
            // Fallback if the target theme doesn't define a radio button drawable.
            // Perhaps an application specific drawable should be used instead of null
            mRadioDrawable = null;
        }

        // Careful with resources like this, we don't need any memory leaks.
        typedArray.recycle();

        mIsChecked = false;
    }


    /*
     * (non-Javadoc)
     * @see android.widget.Checkable#isChecked()
     */
    public boolean isChecked() {
        return mIsChecked;
    }


    /*
     * (non-Javadoc)
     * @see android.view.View#onAttachedToWindow()
     */
    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();

        // Check if there is a valid GUI element that can visualize the current check-state.
        if (mCheckedTextView != null) {
            ViewParent p = getParent();

            // Check if the parent of this list item is a ListView
            if (p instanceof ListView) {
                int choiceMode = ((ListView) p).getChoiceMode();

                // Decide which check-state notation to visualize (check box, radio button or none).
                switch (choiceMode) {
                    case ListView.CHOICE_MODE_MULTIPLE:
                        mCheckedTextView.setCheckMarkDrawable(mCheckDrawable);
                        break;

                    case ListView.CHOICE_MODE_SINGLE:
                        mCheckedTextView.setCheckMarkDrawable(mRadioDrawable);
                        break;

                    default:
                        mCheckedTextView.setCheckMarkDrawable(null);
                        break;
                }
            }
        }
    }


    /*
     * (non-Javadoc)
     * @see android.view.View#onFinishInflate()
     */
    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        mCheckedTextView = (CheckedTextView) findViewById(android.R.id.text1);
    }


    /*
     * (non-Javadoc)
     * @see android.widget.Checkable#setChecked(boolean)
     */
    public void setChecked(boolean checked) {
        mIsChecked = checked;

        if (mCheckedTextView != null) {
            mCheckedTextView.setChecked(mIsChecked);
        }
    }


    /*
     * (non-Javadoc)
     * @see android.widget.Checkable#toggle()
     */
    public void toggle() {
        setChecked(!mIsChecked);
    }

}

exampleListView.xml

请注意!如果您将android:choiceMode属性设置为"multipleChoice",则会自动获取复选框;如果您将其设置为"singleChoice",则会自动获取复选框,前提是您使用上述实现。

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ListView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:choiceMode="singleChoice"
        android:id="@+id/myList" />

</LinearLayout>

奖励: MyCustomAdapter :: getView()

这个依赖于Cursor。当然,您将根据自己的需要实施它。

private final class ViewHolder {
    public ImageView iconView;
    public TextView titleView;
    public TextView descriptionView;
}


/*
 * (non-Javadoc)
 * @see android.widget.Adapter#getView(int, android.view.View, android.view.ViewGroup)
 */
public View getView(int position, View convertView, ViewGroup parent) {
    View view = null;

    // Only do something if the requested position exists within the Cursor.
    if (mCursor.moveToPosition(position)) {
        ViewHolder viewHolder;
        view = convertView;

        if (view == null) {
            // Create and initialize a new view if not created already for this position.
            view = mLayoutInflater.inflate(R.layout.listitem, null);

            // Don't "find view by id" each and every time, but rather save a reference
            // to them and associate the references with the list item itself by storing 
            // them in the list items "tag" attribute. When the view is re-used later on, 
            // you already have a reference to its views and don't need to find them 
            // again, which is a time-consuming operation.
            viewHolder = new ViewHolder();
            viewHolder.iconView = (ImageView) view.findViewById(R.id.myIcon);
            viewHolder.titleView = (TextView) view.findViewById(R.id.myTitle);
            viewHolder.descriptionView = (TextView) view.findViewById(R.id.myDescr);

            view.setTag(viewHolder);
        }
        else {
            // Get the references to the views for this, already existing list item.
            viewHolder = (ViewHolder) view.getTag();
        }

        // Create a bitmap from the byte array in the database.
        byte[] buffer = mCursor.getBlob(mIconColumnIndex);
        Bitmap icon = null;

        // Try to decode the byte array if it exists.
        if (buffer != null) {
            icon = BitmapFactory.decodeByteArray(buffer, 0, buffer.length);
        }

        // Update the views with new data.
        viewHolder.iconView.setImageBitmap(icon);

        String title = mCursor.getString(mTitleColumnIndex);
        viewHolder.titleView.setText(title);

        String description = mCursor.getString(mDescriptionColumnIndex);
        viewHolder.descriptionView.setText(description);
    }

    // Return a view showing the correct data for the item at 'position'.
    return view;
}

原始答案:

我可以建议这个链接:

http://tokudu.com/2010/android-checkable-linear-layout/

当我处于你的确切位置时,我自己非常高兴:-)如果还有什么不清楚,请随时指出你的问题,我很乐意尝试帮助或协助进一步的代码示例(就像前面提到:几天前我就一直在你的位置。)

答案 1 :(得分:3)

我使用dbm's answer除了一件事,它对我来说很好:

您应该使用CheckedTextView方法启动onAttachedToWindow(),而不是onFinishInflate().这是因为onAttachedToWindow()onFinishInflate()之前调用并使用上面的解决方案永远不会在CheckedTextView中看到任何可绘制的内容 - 在调用onAttachedToWindow()时它为空。