The simplest ListView to achieve single and multiple selection effects

1. No picture, no truth
Single selection display effect
Multiple selection display effect
2. Key code
1. Main layout sample_main.xml (single-choice and multi-choice switching, set android:choiceMode, other unchanged)

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:showDividers="middle"
    android:divider="?android:dividerHorizontal">

    <TextView style="@style/Widget.DescriptionBar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/intro_message" />

    <!--
      当 ListView 已设置 choiceMode 时,它将允许用户"选择"
      一个或多个项目。该框架提供了默认列表项目布局,这显示标准单选按钮或复选框旁边
      单行文本:
       《 android:choiceMode="singleChoice"》
      R.layout.simple_list_item_single_choice 和
      《  android:choiceMode="multipleChoice"》
      R.layout.simple_list_item_multiple_choice。
      应该设置 android: scrollbarStyle (显示和隐藏)
       android:scrollbarStyle="outsideInset"不显示
       android:scrollbarStyle="insideOverlay"显示
    -->
    <ListView android:id="@+id/listview"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:paddingLeft="@dimen/page_margin"
        android:paddingRight="@dimen/page_margin"
        android:scrollbarStyle="outsideInset"
        android:choiceMode="multipleChoice" />
</LinearLayout>

2.item layout

<!--
  从 sample_main.xml ListView 有 choiceMode 套,意思说当用户
选择列表项,列表视图将设置为该项目的根视图状态
(此 CheckableLinearLayout)"检查"。请注意,这需要查看
实现的接口。一旦选中根视图,则任何item,
有 duplicateParentState 属性设置的将继承此"选中"状态.
-->
<com.example.android.customchoicelist.CheckableLinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="8dp"
    android:id="@+id/ll_contain"
    android:paddingRight="8dp"
    android:minHeight="?android:listPreferredItemHeight"
    android:gravity="center_vertical">

    <TextView android:id="@android:id/text1"
        android:duplicateParentState="true"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:textAppearance="?android:textAppearanceMedium"
        android:textColor="@color/hideable_text_color" />

    <ImageView android:src="@drawable/ic_hideable_item"
        android:duplicateParentState="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="16dp" />

</com.example.android.customchoicelist.CheckableLinearLayout>

3. Customize single-selection and multi-selection layouts

package com.example.android.customchoicelist;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.Checkable;
import android.widget.LinearLayout;

/**
 *自定义单选和多选布局
 */
public class CheckableLinearLayout extends LinearLayout implements Checkable {
    private static final int[] CHECKED_STATE_SET = {android.R.attr.state_checked};

    private boolean mChecked = false;

    public CheckableLinearLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
    //返回选中的状态
    public boolean isChecked() {
        return mChecked;
    }
    //设置选中的状态
    public void setChecked(boolean b) {
        if (b != mChecked) {
            mChecked = b;
            refreshDrawableState();
        }
    }
    //选择开关
    public void toggle() {
        setChecked(!mChecked);
    }
    //添加选中的条目状态
    @Override
    public int[] onCreateDrawableState(int extraSpace) {
        final int[] drawableState = super.onCreateDrawableState(extraSpace + 1);
        if (isChecked()) {
            mergeDrawableStates(drawableState, CHECKED_STATE_SET);
        }
        return drawableState;
    }
}

4. Main code MainActivity.java

package com.example.android.customchoicelist;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;



/**
 *如何创建自定义的单或多选择
 * @author  孤狼
 * @since  2015-8-3
 */
public class MainActivity extends Activity {
    ListView listView;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sample_main);
        listView =(ListView)findViewById(R.id.listview);
        listView.setAdapter(new MyAdapter());
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //获取条目
                CheckableLinearLayout linearLayout = (CheckableLinearLayout) view.findViewById(R.id.ll_contain);
                if (linearLayout.isChecked()) {
                    Log.e("选中true", position + "");
                } else {
                    Log.e("未选中false", position + "");
                }
                /**对于多选,建议创建集合,用于封装用户选中的条目position,存入时判定                     用户来回切换的状态*/
            }
        });
    }

    /**
     * A simple array adapter that creates a list of cheeses.
     */
    private class MyAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return Cheeses.CHEESES.length;
        }

        @Override
        public String getItem(int position) {
            return Cheeses.CHEESES[position];
        }

        @Override
        public long getItemId(int position) {
            return Cheeses.CHEESES[position].hashCode();
        }

        @Override
        public View getView(int position, View convertView, ViewGroup container) {
            if (convertView == null) {
                convertView = getLayoutInflater().inflate(R.layout.list_item, container, false);
            }
            ((TextView) convertView.findViewById(android.R.id.text1))
                    .setText(getItem(position));
            return convertView;
        }
    }
}

3. Description There is no unnecessary nonsense
throughout the article, and no waste of everyone's precious time. The code is concise and the main parts are commented. The needs in actual development need to be customized and played by the cattle. If you have any questions, please leave a message - Gu Wolf

4. Sample source code (because Lone Wolf uses Android studio development, there is no eclipse version for the time being)

Download the sample source code

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325408871&siteId=291194637