从ListView获取EditText值

时间:2012-12-25 12:07:54

标签: android listview android-edittext android-arrayadapter

我正在尝试从ListView中的EditTexts获取值,但它无法正常工作。在afterTextChanged方法中设置为'lista'数组的值显然已丢失。我是android编程的新手,有人可以帮帮我吗? (抱歉英文不好) 下面是适配器中getView的代码:

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder holder;

    final int posicao = position;

    if (convertView == null) {
        LayoutInflater inflater = contexto.getLayoutInflater();
        convertView = inflater.inflate(R.layout.produtos, null);
        holder = new ViewHolder();
        holder.texto = (TextView) convertView.findViewById(R.id.txtDescricao);
        holder.checkbox = (CheckBox) convertView.findViewById(R.id.chkProduto);
        holder.edit = (EditText) convertView.findViewById(R.id.txtValor);
        convertView.setTag(holder);
    } else {
        holder = (ViewHolder) convertView.getTag();
    }
    holder.texto.setText(getItem(position).getTexto());     

    holder.edit.setText("0");
    holder.edit.setTag(new LinhaItemTag(getItem(position), position));  

//here a get an exception just setting the focus on edit
holder.edit.setOnFocusChangeListener(new OnFocusChangeListener() {
        public void onFocusChange(View v, boolean hasFocus) {
            int posicao = v.getId();
            EditText e = ((EditText) v);
            if (!e.getText().toString().equals("")) {
                if (hasFocus) {
                    if(e.getText().toString().length() != 0)
                        lista.get(posicao).setValor(Double.parseDouble(e.getText().toString()));
                }
            }

        }
    });

    holder.edit.addTextChangedListener( new TextWatcher() {             

        public void afterTextChanged(Editable s)
        {           

            if(s.length() != 0) 
            {
                lista.get(posicao).setValor(Double.parseDouble(s.toString()));              
            }


        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                int count) {
            // TODO Auto-generated method stub

        }
    }); 


    holder.checkbox.setOnCheckedChangeListener(null);
    holder.checkbox.setChecked(getItem(position).Selecionado());
    holder.checkbox.setTag(new LinhaItemTag(getItem(position), position));

    holder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            LinhaItemTag elemento = (LinhaItemTag) buttonView.getTag();
            elemento.item.setSelecionado(isChecked);

            if (isChecked) {
                pegos[elemento.position] = true;                
            } else {
                pegos[elemento.position] = false;
            }
            boolean checados = true;
            for (int i = 0; i < lista.size(); i++) {
                if (!pegos[i]) {
                    checados = false;
                    break;
                }
            }
            if (checados) {
                for(int i = 0; i < lista.size(); i++)
                {                   
                    total += lista.get(i).getValor();
                }
                Toast.makeText(contexto, "Compra finalizada - Valor Total: " + total, Toast.LENGTH_LONG).show();
            }
        }
    });

    return convertView;
}

}

我设法从EditTexts中查看此帖子的值:how to retrieve value from all EditText in ListView 现在,我遇到了其他问题:当我滚动列表时,EditTexts中的值丢失了。 这就像我现在的代码一样:

public class MeuAdapter extends ArrayAdapter<LinhaItem> {

private final List<LinhaItem> lista;
private final Activity contexto;
private final boolean[] pegos;
private final double[] valores;
double total;

public MeuAdapter(Activity contexto, List<LinhaItem> lista) {
    super(contexto, 0, lista);
    this.contexto = contexto;
    this.lista = lista;
    pegos = new boolean[lista.size()];
    valores = new double[lista.size()];
    for (int i = 0; i < lista.size(); i++) {
        pegos[i] = false;
        valores[i] = 0;
    }
    total = 0;
}

public class ViewHolder
{
    protected TextView texto;
    protected CheckBox checkbox;
    protected EditText edit;
}

public class LinhaItemTag {

    LinhaItem item;
    int position;

    LinhaItemTag(LinhaItem item, int position) {
        this.item = item;
        this.position = position;
    }
}

private class MeuTextWatcher implements TextWatcher {

    private View v; 

    public MeuTextWatcher(View v)
    {
        this.v = v;     
    }

    @Override
    public void afterTextChanged(Editable e) {
        String s = e.toString();
        LinhaItemTag lTag = (LinhaItemTag) v.getTag();      
        if(s.length() != 0)
        {           
            valores[lTag.position] = Double.parseDouble(s);         
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count,
            int after) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before,
            int count) {
        // TODO Auto-generated method stub

    }

}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder holder;  

    if (convertView == null) {
        LayoutInflater inflater = contexto.getLayoutInflater();
        convertView = inflater.inflate(R.layout.produtos, null);
        holder = new ViewHolder();
        holder.texto = (TextView) convertView.findViewById(R.id.txtDescricao);
        holder.checkbox = (CheckBox) convertView.findViewById(R.id.chkProduto);
        holder.edit = (EditText) convertView.findViewById(R.id.txtValor);
        convertView.setTag(holder);
    } else {
        holder = (ViewHolder) convertView.getTag();
    }
    holder.texto.setText(getItem(position).getTexto()); 

    holder.edit.setText("");
    holder.edit.setTag(new LinhaItemTag(getItem(position), position));      

    holder.edit.addTextChangedListener(new MeuTextWatcher(holder.edit));    


    holder.checkbox.setOnCheckedChangeListener(null);
    holder.checkbox.setChecked(getItem(position).Selecionado());
    holder.checkbox.setTag(new LinhaItemTag(getItem(position), position));

    holder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            LinhaItemTag elemento = (LinhaItemTag) buttonView.getTag();
            elemento.item.setSelecionado(isChecked);

            if (isChecked) {
                pegos[elemento.position] = true;                
            } else {
                pegos[elemento.position] = false;
            }
            boolean checados = true;
            for (int i = 0; i < lista.size(); i++) {
                if (!pegos[i]) {
                    checados = false;
                    break;
                }
            }
            String vlrs = "";
            if (checados) {
                for(int i = 0; i < lista.size(); i++)
                {                   
                    total += valores[i];                    
                }
                Toast.makeText(contexto, "Total da compra: " + total, Toast.LENGTH_LONG).show();
            }
        }
    });

    return convertView;
}

}

我更改了一行:

holder.edit.setText("");

为:

//the valores array is where i store the values in the afterTextChanged method in the TextWatcher class implementation.
holder.edit.setText(**Double.toString(valores[position])**);

但是这不能像我预期的那样工作,例如,如果我为ListView的第一行的EditText设置一个值,这个值在我滚动列表之后被设置为第三行的EditText。列表...

4 个答案:

答案 0 :(得分:15)

要获取EditTextListView的值,您可以在活动中执行此操作。您必须在某些视图上点击或某些东西需要值。所以每当发生这种情况时,只需编写以下代码

View view=listView.getChildAt(position);
EditText editText=view.findViewById(R.id.editText);
String string=editText.getText().toString();

在此处,上面的代码将为您提供EditText position位置ListView中的for(int i=0;i<items.size();i++){ View view=listView.getChildAt(i); EditText editText=view.findViewById(R.id.editText); String string=editText.getText().toString(); if(!string.equals("")) total+=Double.parseDouble(string); } 文字。在检查完所有内容时,您似乎需要EditTexts值的总和?你可以使用这样的东西

{{1}}

答案 1 :(得分:1)

适配器类getView()方法的变化看起来像。

 @Override
public View getView(final int position, View view, ViewGroup parent) {

    TextView txt_id, txt_courny_symbol, txt_member_view;
    EditText edit_member_amount;

    final int posicao = position;
    Log.v("ConvertView", String.valueOf(posicao));


    inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    view = inflater.inflate(R.layout.list_member_layout, null);
    txt_id = (TextView) view.findViewById(R.id.txt_id);
    txt_courny_symbol = (TextView) view.findViewById(R.id.txt_courny_symbol);
    edit_member_amount = (EditText) view.findViewById(R.id.edit_member_amount);

    edit_member_amount.setTag(new LinhaItemTag(getItem(posicao), posicao));
    edit_member_amount.addTextChangedListener(new MeuTextWatcher(edit_member_amount));

    if (al_contact.size() != 0) {
        MemberClass memberClass = al_contact.get(position);
        txt_id.setText(memberClass.getName());
        txt_courny_symbol.setText(sym);
    }

    return view;

}
  

删除我们的ViewHolder类

答案 2 :(得分:0)

您可以使用下面的代码执行此操作,listview无法在行上保存控制器状态,因此您需要使用settag和gettag控件。

来源:https://dl.dropbox.com/u/68130108/ListViewEditItem.rar

http://i.stack.imgur.com/DqKv3.png

答案 3 :(得分:0)

从EditTexts中丢失值可能会令人讨厌。我在工作时找到了这个解决方案。

在您的Android清单中,选择列表视图所在的活动。然后将此代码块放在那里。

android:windowSoftInputMode="adjustPan"

然后转到ListView,然后导航到xml布局并将此块放在那里。

android:descendantFocusability="beforeDescendants"