详谈Android ListView的选择模式

效果图:

ListView 定义了choiceMode属性,描述是这样的:

用于为视图定义选择行为。默认情况下,列表时没有任何选择行为的。如果把choiceMode设置为singleChoice,列表允许有一个列表项处于被选状态。如果把choiceMode设置为multipleChoice,那么列表允许有任意数量的列表项处于被选状态

ListView以某种方式通过Checkable接口处理视图的选择状态,LIstView源码中有这么一段:

 if (mChoiceMode != CHOICE_MODE_NONE && mCheckStates != null) {
      if (child instanceof Checkable) {
        ((Checkable) child).setChecked(mCheckStates.get(position));
      } else if (getContext().getApplicationInfo().targetSdkVersion
          >= android.os.Build.VERSION_CODES.HONEYCOMB) {
        child.setActivated(mCheckStates.get(position));
      }
    }

如果需要ListView处理选择行为,需要令列表项对应的自定义视图实现Checkable接口,这个需要自定义

创建一个Countries.java

public class Countries {
 public static final String[] COUNTRIES = new String[] {
   "Afghanistan", "Albania", "Algeria", "American Samoa", "Andorra",
   "Angola", "Anguilla", "Antarctica", "Antigua and Barbuda",
   "Argentina", "Armenia", "Aruba", "Australia", "Austria",
   "Azerbaijan", "Bahrain", "Bangladesh", "Barbados", "Belarus",
   "Belgium", "Belize", "Benin", "Bermuda", "Bhutan", "Bolivia",
   "Bosnia and Herzegovina", "Botswana", "Bouvet Island", "Brazil",
   "British Indian Ocean Territory", "British Virgin Islands",
   "Brunei", "Bulgaria", "Burkina Faso", "Burundi", "Cote d'Ivoire",
   "Cambodia", "Cameroon", "Canada", "Cape Verde", "Cayman Islands",
   "Central African Republic", "Chad", "Chile", "China",
   "Christmas Island", "Cocos (Keeling) Islands", "Colombia",
   "Comoros", "Congo", "Cook Islands", "Costa Rica", "Croatia",
   "Cuba", "Cyprus", "Czech Republic",
   "Democratic Republic of the Congo", "Denmark", "Djibouti",
   "Dominica", "Dominican Republic", "East Timor", "Ecuador",
   "Egypt", "El Salvador", "Equatorial Guinea", "Eritrea",
   "Estonia", "Ethiopia", "Faeroe Islands", "Falkland Islands",
   "Fiji", "Finland", "Former Yugoslav Republic of Macedonia",
   "France", "French Guiana", "French Polynesia",
   "French Southern Territories", "Gabon", "Georgia", "Germany",
   "Ghana", "Gibraltar", "Greece", "Greenland", "Grenada",
   "Guadeloupe", "Guam", "Guatemala", "Guinea", "Guinea-Bissau",
   "Guyana", "Haiti", "Heard Island and McDonald Islands",
   "Honduras", "Hong Kong", "Hungary", "Iceland", "India",
   "Indonesia", "Iran", "Iraq", "Ireland", "Israel", "Italy",
   "Jamaica", "Japan", "Jordan", "Kazakhstan", "Kenya", "Kiribati",
   "Kuwait", "Kyrgyzstan", "Laos", "Latvia", "Lebanon", "Lesotho",
   "Liberia", "Libya", "Liechtenstein", "Lithuania", "Luxembourg",
   "Macau", "Madagascar", "Malawi", "Malaysia", "Maldives", "Mali",
   "Malta", "Marshall Islands", "Martinique", "Mauritania",
   "Mauritius", "Mayotte", "Mexico", "Micronesia", "Moldova",
   "Monaco", "Mongolia", "Montserrat", "Morocco", "Mozambique",
   "Myanmar", "Namibia", "Nauru", "Nepal", "Netherlands",
   "Netherlands Antilles", "New Caledonia", "New Zealand",
   "Nicaragua", "Niger", "Nigeria", "Niue", "Norfolk Island",
   "North Korea", "Northern Marianas", "Norway", "Oman", "Pakistan",
   "Palau", "Panama", "Papua New Guinea", "Paraguay", "Peru",
   "Philippines", "Pitcairn Islands", "Poland", "Portugal",
   "Puerto Rico", "Qatar", "Reunion", "Romania", "Russia", "Rwanda",
   "Sqo Tome and Principe", "Saint Helena", "Saint Kitts and Nevis",
   "Saint Lucia", "Saint Pierre and Miquelon",
   "Saint Vincent and the Grenadines", "Samoa", "San Marino",
   "Saudi Arabia", "Senegal", "Seychelles", "Sierra Leone",
   "Singapore", "Slovakia", "Slovenia", "Solomon Islands",
   "Somalia", "South Africa",
   "South Georgia and the South Sandwich Islands", "South Korea",
   "Spain", "Sri Lanka", "Sudan", "Suriname",
   "Svalbard and Jan Mayen", "Swaziland", "Sweden", "Switzerland",
   "Syria", "Taiwan", "Tajikistan", "Tanzania", "Thailand",
   "The Bahamas", "The Gambia", "Togo", "Tokelau", "Tonga",
   "Trinidad and Tobago", "Tunisia", "Turkey", "Turkmenistan",
   "Turks and Caicos Islands", "Tuvalu", "Virgin Islands", "Uganda",
   "Ukraine", "United Arab Emirates", "United Kingdom",
   "United States", "United States Minor Outlying Islands",
   "Uruguay", "Uzbekistan", "Vanuatu", "Vatican City", "Venezuela",
   "Vietnam", "Wallis and Futuna", "Western Sahara", "Yemen",
   "Yugoslavia", "Zambia", "Zimbabwe" };
}

在view文件夹下创建一个CountryView.java

public class CountryView extends LinearLayout implements Checkable {

 private TextView mTitle;
 private CheckBox mCheckBox;

 public CountryView(Context context) {
  this(context, null);
 }

 public CountryView(Context context, AttributeSet attrs) {
  super(context, attrs);
  LayoutInflater inflater = LayoutInflater.from(context);
  View v = inflater.inflate(R.layout.country_view, this, true);
  mTitle = (TextView) v.findViewById(R.id.country_view_title);
  mCheckBox = (CheckBox) v.findViewById(R.id.country_view_checkbox);
 }

 public void setTitle(String title) {
  mTitle.setText(title);
 }

 @Override
 public boolean isChecked() {
  return mCheckBox.isChecked();
 }

 @Override
 public void setChecked(boolean checked) {
  mCheckBox.setChecked(checked);
 }

 @Override
 public void toggle() {
  mCheckBox.toggle();
 }

}

在adapter文件夹下 CountryAdapter

public class CountryAdapter extends ArrayAdapter<Country> {

 public CountryAdapter(Context context, int textViewResourceId,
   List<Country> objects) {
  super(context, textViewResourceId, objects);
 }

 @Override
 public View getView(int position, View convertView, ViewGroup parent) {
  if ( convertView == null ) {
   convertView = new CountryView(getContext());
  }

  Country country = getItem(position);

  CountryView countryView = (CountryView) convertView;
  countryView.setTitle(country.getName());

  return convertView;
 }
}

在model文件夹下Country.java

public class Country {
 private String name;

 public Country() {

 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

}

主界面

public class Hack30Activity extends Activity {
  private ListView mListView;
  private CountryAdapter mAdapter;
  private List<Country> mCountries;
  private String mToastFmt;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_hack30);
    createCountriesList();
    mToastFmt = getString(R.string.activity_main_toast_fmt);
    mAdapter = new CountryAdapter(this, -1, mCountries);
    mListView = (ListView) findViewById(R.id.activity_main_list);
    mListView.setAdapter(mAdapter);
  }

  public void onPickCountryClick(View v) {
    int pos = mListView.getCheckedItemPosition();

    if (ListView.INVALID_POSITION != pos) {
      String msg = String.format(mToastFmt, mCountries.get(pos)
          .getName());
      Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }
  }

  private void createCountriesList() {
    mCountries = new ArrayList<Country>(Countries.COUNTRIES.length);
    for (int i = 0; i < Countries.COUNTRIES.length; i++) {
      Country country = new Country();
      country.setName(Countries.COUNTRIES[i]);
      mCountries.add(country);
    }
  }
}

country_view.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:orientation="horizontal" >

  <TextView
    android:id="@+id/country_view_title"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="0.9"
    android:padding="10dp" />

  <CheckBox
    android:id="@+id/country_view_checkbox"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="0.1"
    android:clickable="false"
    android:focusable="false"
    android:focusableInTouchMode="false"
    android:gravity="center_vertical"
    android:padding="10dp" />

</LinearLayout>

activity_hack30.xml

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

  <Button
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:onClick="onPickCountryClick"
    android:text="@string/activity_main_add_selection" />

  <ListView
    android:id="@+id/activity_main_list"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:choiceMode="singleChoice" />

</LinearLayout>

<string name="activity_main_toast_fmt">Chosen country: %s</string>
  <string name="activity_main_add_selection">Pick Country</string>

以上这篇详谈Android ListView的选择模式就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • Android ListView 默认选中某一项实现代码

    这里是使用 TOC 生成的目录: •Layout文件定义 ◦ListView定义 ◦item 模板定义 •代码 ◦初始化列表 ◦用户点击处理 •效果 -------------------------------------------------------------------------------- 要使用 ListView 实现一个充值方式选择,默认想选中第二项,搞了一下午,终于搞定了.原本就没怎么用 Java 写过 Android 应用,又隔了好久没写,一切都生疏了,半吊子变成大呆

  • Android ListView构建支持单选和多选的投票项目

    引言 我们在android的APP开发中有时候会碰到提供一个选项列表供用户选择的需求,如在投票类型的项目中,我们提供一些主题给用户选择,每个主题有若干选项,用户对这些主题的选项进行选择,然后提交. 本文以一个支持单选和多选投票项目为例,演示了在一个ListView中如何构建CheckBox列表和RadioButton列表,并分析了实现的原理和思路,提供有需要的朋友参考. 项目的演示效果如下. 数据源 通常我们的数据源来自于数据库.首先,我们构建投票项目类SubjectItem. /** * 主题

  • Android ListView优化之提高android应用效率

    ListView是一个经常用到的控件,ListView里面的每个子项Item可以使一个字符串,也可以是一个组合控件.Adapter是listview和数据源间的中间人. 当每条数据进入可见区域时,adapter的getview()会被调用,返回代表具体数据的视图.触摸滚动时,频繁调用.支持成百上千条数据. 下面为显示每条数据的xml文件: <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

  • listview 选中高亮显示实现方法

    人人客户端有一个很好的导航栏,如下图所示,当点击左侧ListView后,选中的一行就会一直呈高亮状态显示,图中选中行字的颜色显示为蓝色(注意:是选中行后一直高亮,而不是只是点击时高亮),如果再次点击另外的一行, 则新的那一行就高亮,下面就来实现这个高亮效果的显示:  刚开始实现的时候,我打算使用ListView的 getChildAt(int pos)方法来实现,结果发现非常的cao蛋,因为ListView本身的原因,当你View view=listView.getChildAt(pos),并且

  • android listview优化几种写法详细介绍

    这篇文章只是总结下getView里面优化视图的几种写法,就像孔乙己写茴香豆的茴字的几种写法一样,高手勿喷,勿笑,只是拿出来分享,有错误的地方欢迎大家指正,谢谢. listview Aviewthatshowsitemsinaverticallyscrollinglist. 一个显示一个垂直的滚动子项的列表视图在android开发中,使用listview的地方很多,用它来展现数据,成一个垂直的视图.使用listview是一个标准的适配器模式,用数据--,界面--xml以及适配器--adapter,

  • 详谈Android ListView的选择模式

    效果图: ListView 定义了choiceMode属性,描述是这样的: 用于为视图定义选择行为.默认情况下,列表时没有任何选择行为的.如果把choiceMode设置为singleChoice,列表允许有一个列表项处于被选状态.如果把choiceMode设置为multipleChoice,那么列表允许有任意数量的列表项处于被选状态 ListView以某种方式通过Checkable接口处理视图的选择状态,LIstView源码中有这么一段: if (mChoiceMode != CHOICE_MO

  • Android ListView中动态添加RaidoButton的实例详解

    Android ListView中动态添加RaidoButton的实例详解 这里讲解的内容是:从数据库中取得数据,将这些数据的value值赋值给Radiobutton的text属性,将这些数据的key值赋值给radiobutton的key值.同时实现点击一整行,更换radiobutton选择. XML代码:主要是添加一个ListView控件 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android&q

  • Android Spinner列表选择框的应用

    Android  Spinner列表选择框的应用 Spinner 是 Android 的列表选择框,不过 spinner 并不需要显示下拉列表,而是相当于弹出一个菜单供用户选择. Spinner 属性: ● android:spinnerMode:列表显示的模式,有两个选择,为弹出列表(dialog)以及下拉列表(dropdown),如果不特别设置,为下拉列表. ● android:entries:使用<string-array.../>资源配置数据源. ● android:prompt:对当

  • Android ListView实现单选及多选等功能示例

    本文实例讲述了Android ListView实现单选及多选等功能的方法.分享给大家供大家参考,具体如下: 在项目中也遇到过给ListView的item添加选择功能.比如一个网购APP,有个历史浏览页面,这个页面现点击item单选/多选及全选删除功能. 当时也是通过在数据中添加一个是否选择的字段来记录item的状态,然后根据这个字段有相应的position位置进行选择状态更改及删除操作. 刚刚看了Android API Demos中17种ListView的实现方法,发现ListView自身就带有

  • Android  Spinner列表选择框的应用

    Android  Spinner列表选择框的应用 Spinner 是 Android 的列表选择框,不过 spinner 并不需要显示下拉列表,而是相当于弹出一个菜单供用户选择. Spinner 属性: ● android:spinnerMode:列表显示的模式,有两个选择,为弹出列表(dialog)以及下拉列表(dropdown),如果不特别设置,为下拉列表. ● android:entries:使用<string-array.../>资源配置数据源. ● android:prompt:对当

  • Android listview与adapter详解及实例代码

    一个ListView通常有两个职责. (1)将数据填充到布局. (2)处理用户的选择点击等操作. 第一点很好理解,ListView就是实现这个功能的.第二点也不难做到,在后面的学习中读者会发现,这非常简单. 一个ListView的创建需要3个元素. (1)ListView中的每一列的View. (2)填入View的数据或者图片等. (3)连接数据与ListView的适配器. 也就是说,要使用ListView,首先要了解什么是适配器.适配器是一个连接数据和AdapterView(ListView就

  • Android仿微信选择图片和拍照功能

    本文实例为大家分享了 Android微信选择图片的具体代码,和微信拍照功能,供大家参考,具体内容如下 1.Android6.0系统,对于权限的使用都是需要申请,选择图片和拍照需要申请Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE这两个权限. if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageM

  • Android ListView监听滑动事件的方法(详解)

    ListView的主要有两种滑动事件监听方法,OnTouchListener和OnScrollListener 1.OnTouchListener OnTouchListener方法来自View中的监听事件,可以在监听三个Action事件发生时通过MotionEvent的getX()方法或getY()方法获取到当前触摸的坐标值,来对用户的滑动方向进行判断,并可在不同的Action状态中做出相应的处理 mListView.setOnTouchListener(new View.OnTouchLis

  • Android ListView添加头布局和脚布局实例详解

    Android ListView添加头布局和脚布局 之前学习喜马拉雅的时候做的一个小Demo,贴出来,供大家学习参考: 如果我们当前的页面有多个接口.多种布局的话,我们一般的选择无非就是1.多布局:2.各种复杂滑动布局外面套一层ScrollView(好low):3.头布局脚布局.有的时候我们用多布局并不能很好的实现,所以头布局跟脚布局就是我们最好的选择了:学过了ListView的话原理很简单,没啥理解的东西,直接贴代码了: 效果图: 正文部分布局: fragment_classify.xml <

  • 详谈Android动画效果translate、scale、alpha、rotate

    动画类型 Android的animation由四种类型组成 XML中 alpha 渐变透明度动画效果 scale 渐变尺寸伸缩动画效果 translate 画面转换位置移动动画效果 rotate 画面转移旋转动画效果 JavaCode中 AlphaAnimation 渐变透明度动画效果 ScaleAnimation 渐变尺寸伸缩动画效果 TranslateAnimation 画面转换位置移动动画效果 RotateAnimation 画面转移旋转动画效果 Android动画模式 Animation

随机推荐