繁体   English   中英

如何在单击按钮时获取ListView项目?

[英]How to get ListView items on button click?

我有一个带有CheckBoxEditTextListView 我想在单击Button获取选中的CheckBoxes的名称和EditText值。 我怎样才能做到这一点?

我的getView()方法:

@Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        LayoutInflater inflater = ((Activity) context).getLayoutInflater();
        convertView = inflater.inflate(R.layout.scrap_list_row_item, parent, false);
        final EditText kg = (EditText) convertView.findViewById(R.id.editText1);
        final CheckBox cb = (CheckBox) convertView.findViewById(R.id.checkBox1);
        final TextView txtKg = (TextView) convertView.findViewById(R.id.textView1);
        final float scale = context.getResources().getDisplayMetrics().density;
        cb.setPadding(cb.getPaddingLeft() + (int)(10.0f * scale + 0.5f),
                cb.getPaddingTop(),
                cb.getPaddingRight(),
                cb.getPaddingBottom());
        //cb.setText(modelItems[position].getName());
        cb.setText(arrayScrapItems.get(position).getItemName());

        cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

               @Override
               public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
                   if(isChecked)
                   {
                      // Toast.makeText(context, "You checked " + arrayScrapItems.get(position).getItemName(), Toast.LENGTH_SHORT).show();
                       cb.setButtonDrawable(R.drawable.checkbox_background_active);
                       kg.setBackgroundResource((R.drawable.kg_box));
                       txtKg.setTextColor(Color.parseColor("#000000"));
                       kg.setFocusable(true);
                       kg.setEnabled(true);
                   }
                   else
                   {
                       //Toast.makeText(context, "You unchecked " + arrayScrapItems.get(position).getItemName(), Toast.LENGTH_SHORT).show();
                       cb.setButtonDrawable(R.drawable.checkbox_background);
                       kg.setBackgroundResource((R.drawable.kg_box_inactive));
                       txtKg.setTextColor(Color.parseColor("#D3D3D3"));
                       kg.setFocusable(false);
                       kg.setEnabled(false);
                   }
               }
           }
        ); 

        return convertView;

当ListView循环使用它的视图时,您不能单击按钮,浏览所有列表项并查看它们是否被选中,因为列表中只有太多的视图,因此可见行。 例如,如果您的列表有1000行并且可以在屏幕上同时显示其中的20行,则ListView仅具有20个视图(即20个CheckBox和20个EditText),并且取决于ListAdapter实现,才能用正确的数据填充它们1000行中的任何行,具体取决于用户滚动列表的距离。

因此,您将必须在某种非屏幕模型中跟踪选中的行及其文本。

当您在模型中拥有所有这些信息时,您可以轻松地访问它,单击该按钮。

因此,首先,您需要以仅在convertView为null时才创建新视图的方式来更改代码。 如果不为null,则只需将其View的状态更新为给定position处的行position 此状态应来自您的屏幕外模型。

希望这个答案能使您走上正确的道路,无论如何,您应该熟悉ListViews回收视图的方式。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM