代码之家  ›  专栏  ›  技术社区  ›  Jürgen Steinblock

Android如何从onClickHandler()获取ListView中的行位置

  •  0
  • Jürgen Steinblock  · 技术社区  · 14 年前

    客户是Poco:

    public class Customer {
        public String LastName;
        public boolean IsActive;
    }
    

    工作原理:我已成功将我的ArrayList绑定到我的ListView,LastName显示为文本,复选框是否选中(取决于IsActive),但现在我希望每次选中复选框时都更新ArrayList,但我无法访问OnClickListener中的位置:

    setListAdapter(new ArrayAdapter<Customer>(this, android.R.layout.simple_list_item_checked, items) {
    
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
    
            View row;
            if (null == convertView) {
                row =  mInflater.inflate(android.R.layout.simple_list_item_checked, null);
            } else {
                row = convertView;
            }
    
            CheckedTextView ctv = (CheckedTextView) row.findViewById(android.R.id.text1);
            ctv.setText(getItem(position).LastName);
            ctv.setChecked(getItem(position).IsChecked);
    
            ctv.setOnClickListener(new View.OnClickListener() {
    
                @Override
                public void onClick(View v) {
                    CheckedTextView ctv = (CheckedTextView) v;
                    ctv.toggle();
    
                    // this does not work because I don't have the position
                    getItem(position).IsChecked = (ctv).isChecked();
    
                }
    
            });
    
            return row;
        }
    
    });
    

    setPosition/getPosition 存储位置以供以后使用,甚至添加对相关对象的引用,但我想有一个现有的解决方案我找不到。

    2 回复  |  直到 14 年前
        1
  •  1
  •   WarrenFaith    14 年前

    我不会按行来处理单击,而是按ListActivity来处理

    public void onListItemClick(ListView l, View v, int position, long id)
    

        2
  •  4
  •   Sephy    14 年前

    您应该使用ListView为其提供一个onItemClickListener,并向其传递一个AdapterView,如下所示:

    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    public void onItemClick(AdapterView<?> list, View v, int pos, long id) {
        // here you have th view, the position, everything you need to have fun ;=)
        //you can acces the content of your adapter here with :   
        mAdapter.getItem(pos);
        }
    }