自定义ListView与复选框

时间:2012-12-09 13:57:06

标签: android listview checkbox checked

如何知道Android应用程序中自定义列表视图中的所有复选框何时被检查?我有一个自定义列表视图,我只想知道列表中的所有复选框何时被检查并向用户显示一条消息,对不起我的英语。

这是我的适配器的代码,但它不起作用......

public class MeuAdapter extends ArrayAdapter<LinhaItem>
{

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

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

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent)
    {
        View view = null;
        final int posicao = position;
        if(convertView == null)
        {
            LayoutInflater inflater = contexto.getLayoutInflater();
            view = inflater.inflate(R.layout.produtos, null);
            final ViewHolder viewHolder = new ViewHolder();
            viewHolder.texto = (TextView) view.findViewById(R.id.txtDescricao);
            viewHolder.checkbox = (CheckBox) view.findViewById(R.id.chkProduto);
            viewHolder.edit = (EditText) view.findViewById(R.id.txtValor);

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

                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
                {
                    LinhaItem elemento = (LinhaItem) viewHolder.checkbox.getTag();
                    elemento.setSelecionado(buttonView.isChecked());
                    if(elemento.Selecionado())
                    {
                        pegos[posicao] = true;
                    }
                    total += lista.get(posicao).getValor();

                    boolean cheia = true;

                    for(int i = 0; i < lista.size(); i++)
                    {
                        cheia = pegos[i];
                        //Toast.makeText(contexto, "pego["+i+"]"+pegos[i], 10000).show();
                    }

                    if(cheia)
                    {
                        Toast.makeText(contexto, "Compra finalizada,  valor total: " + total, 10000).show();
                    }
                }   
            });

            view.setTag(viewHolder);
            viewHolder.checkbox.setTag(lista.get(position));

        }
        else
        {
            view = convertView;
            ((ViewHolder) view.getTag()).checkbox.setTag(lista.get(position));
        }
        ViewHolder holder = (ViewHolder) view.getTag();
        holder.texto.setText(lista.get(position).getTexto());
        holder.checkbox.setChecked(lista.get(position).Selecionado());
        holder.edit.setText(Double.toString((lista.get(position).getValor())));



        return view;
    }

}

我的新代码是:

package br.com.boitata.cadastroprodutos;

import java.util.List;
import java.util.ArrayList;

import android.os.Bundle;
import android.app.Activity;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.*;

public class CadastroProdutosActivity extends Activity {

    private Button btnInserir;
    private EditText txtDescricao;
    private EditText txtValor;
    private TextView txtTotal;
    private ListView lstProdutos;
    private ProdutoBD bd;
    private MeuAdapter adapter;

    List<Produto> lista;
    List<LinhaItem> linhas;

    private double total = 0;

    public void preencheLista(List<Produto> lp, ListView lista)
    {
        int tam = lp.size();        
        linhas = new ArrayList<LinhaItem>();

        for(int i = 0; i < tam; i++)
        {
            Produto p = lp.get(i);              
            linhas.add(getLinha(p.getDescricao()));
        }

        adapter = new MeuAdapter(this, linhas);

        //ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, android.R.id.text1, valores);

        lista.setAdapter(adapter);
    }

    public LinhaItem getLinha(String texto)
    {
        return new LinhaItem(texto);
    }   


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cadastro_produtos);

        btnInserir = (Button) findViewById(R.id.btnInserir);
        txtDescricao = (EditText) findViewById(R.id.txtDescricao);
        txtValor = (EditText) findViewById(R.id.txtValor);
        txtTotal = (TextView) findViewById(R.id.txtTotal);
        lstProdutos = (ListView) findViewById(R.id.lstProdutos);

        lstProdutos.setBackgroundColor(Color.BLACK);       


        bd = new ProdutoBD(getApplicationContext());


        lista = bd.listaProdutos();         


        preencheLista(lista, lstProdutos);          


        btnInserir.setOnClickListener(new OnClickListener() {
            public void onClick(View v)
            {
                String checados = "";
                for(int i = 0; i < lista.size(); i++)
                {
                    checados += "pego[" + i + "]" + " " + pegos[i] + " - ";
                }
                Toast.makeText(getApplicationContext(), checados, 40000).show();
            /*  Produto p = new Produto();
                p.setDescricao(txtDescricao.getText().toString());
                p.setValor(Double.parseDouble(txtValor.getText().toString()));
                bd.insere(p);           

                lista = bd.listaProdutos();

                preencheLista(lista, lstProdutos);

                int i = 0;
                total = 0;
                while(i < lista.size())
                {
                    p = lista.get(i);
                    total += p.getValor();
                    i++;
                }

                txtTotal.setText("Total: " + Double.toString(total));*/

            }
        });

    }

    private boolean[] pegos;
    private boolean[] passados;

    public class MeuAdapter extends ArrayAdapter<LinhaItem>
    {

        private final List<LinhaItem> lista;
        private final Activity contexto;        
        private double total = 0;
        private  int qtde = 0;


        public MeuAdapter(Activity contexto, List<LinhaItem> lista)
        {
            super(contexto, R.layout.produtos, lista);
            Toast.makeText(contexto, "Construindo", 10000).show();
            this.contexto = contexto;
            this.lista = lista;
            qtde = this.lista.size();
            pegos = new boolean[qtde];
            passados = new boolean[qtde];
            for(int i = 0; i < this.lista.size(); i++)
            {
                pegos[i] = false;
                passados[i] = false;
            }
        }

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

        @Override
        public View getView(int position, View convertView, ViewGroup parent)
        {
            View view = null;
            final int posicao = position;
            if(convertView == null)
            {
                LayoutInflater inflater = contexto.getLayoutInflater();
                view = inflater.inflate(R.layout.produtos, null);
                final ViewHolder viewHolder = new ViewHolder();
                viewHolder.texto = (TextView) view.findViewById(R.id.txtDescricao);
                viewHolder.checkbox = (CheckBox) view.findViewById(R.id.chkProduto);
                viewHolder.edit = (EditText) view.findViewById(R.id.txtValor);

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

                    @Override
                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
                    {
                        LinhaItem elemento = (LinhaItem) viewHolder.checkbox.getTag();
                        elemento.setSelecionado(buttonView.isChecked());

                        pegos[posicao] = isChecked;

                        if(elemento.Selecionado())
                        {
                            pegos[posicao] = true;
                            qtde--;
                        }
                        else if(qtde < lista.size() && passados[posicao])
                        {
                            qtde++;
                        }                       

                        total += lista.get(posicao).getValor();

                        boolean cheia = true;

                        for(int i = 0; i < lista.size(); i++)
                        {
                            if(!pegos[i])
                            {
                                cheia = false;
                                break;
                            }
                            //Toast.makeText(contexto, "pego["+i+"]"+pegos[i], 10000).show();
                        }

                        if(cheia || qtde == 0)
                        {
                            Toast.makeText(contexto, "Compra finalizada,  valor total: " + total, 10000).show();
                        }

                    //  Toast.makeText(contexto, "Quantidade não selecionada: " + qtde, 5000).show();
                    }   
                });

                view.setTag(viewHolder);
                viewHolder.checkbox.setTag(lista.get(position));

            }
            else
            {
                view = convertView;
                ((ViewHolder) view.getTag()).checkbox.setTag(lista.get(position));
            }
            ViewHolder holder = (ViewHolder) view.getTag();
            holder.texto.setText(lista.get(position).getTexto());
            holder.checkbox.setChecked(lista.get(position).Selecionado());
            holder.edit.setText(Double.toString((lista.get(position).getValor())));

            passados[posicao] = true;

            return view;
        }

    }

}

这适用于当前显示的行...

3 个答案:

答案 0 :(得分:1)

要测试您是否选中了列表行中最后一个未经检查的CheckBox,您可以使用多种方法。这是一个:

boolean allChecked = true;
for(int i = 0; i < lista.size(); i++) {
     if (!pegos[i]) {
          // it appears that one of our ChckBoxes is currently unchecked so
          // we already know that not all CheckBoxes are checked 
          allChecked = false;
          break;
     }
if (allChecked) {
    // if we get here and allChecked is true than all CheckBoxes are checked
    Toast.makeText(contexto, "All checked!!", 10000).show();
}

为避免每次用户检查CheckBox时循环该布尔数组,您可以在适配器中有一个int字段,该字段最初是布尔数组的大小。当用户使用该字段中的CheckBox检查1减少CheckBox时,当用户取消选中1时,您会使用0该字段进行增加。在同一个侦听器中,您将测试该字段是否为CheckBoxes,在这种情况下,所有{{1}}都会被检查。

答案 1 :(得分:0)

您可以使用以下代码 -

public class MeuAdapter extends ArrayAdapter {

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

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

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

    public boolean isAllChecked() {
        boolean allChecked = true;
        for(int i = 0; i < lista.size(); i++) {
             if (!pegos[i]) {
                  allChecked = false;
                  break;
             }
        return allChecked;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent)
    {
        View view = null;
        final int posicao = position;
        if(convertView == null)
        {
            LayoutInflater inflater = contexto.getLayoutInflater();
            view = inflater.inflate(R.layout.produtos, null);
            final ViewHolder viewHolder = new ViewHolder();
            viewHolder.texto = (TextView) view.findViewById(R.id.txtDescricao);
            viewHolder.checkbox = (CheckBox) view.findViewById(R.id.chkProduto);
            viewHolder.edit = (EditText) view.findViewById(R.id.txtValor);

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

                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
                {
                    LinhaItem elemento = (LinhaItem) viewHolder.checkbox.getTag();
                    elemento.setSelecionado(buttonView.isChecked());
                    if(elemento.Selecionado())
                    {
                        pegos[posicao] = true;
                    }
                    total += lista.get(posicao).getValor();

                    boolean cheia = true;

                    for(int i = 0; i < lista.size(); i++)
                    {
                        cheia = pegos[i];
                        //Toast.makeText(contexto, "pego["+i+"]"+pegos[i], 10000).show();
                    }

                    if(cheia)
                    {
                        Toast.makeText(contexto, "Compra finalizada,  valor total: " + total, 10000).show();
                    }
                }   
            });

            view.setTag(viewHolder);
            viewHolder.checkbox.setTag(lista.get(position));

        }
        else
        {
            view = convertView;
            ((ViewHolder) view.getTag()).checkbox.setTag(lista.get(position));
        }
        ViewHolder holder = (ViewHolder) view.getTag();
        holder.texto.setText(lista.get(position).getTexto());
        holder.checkbox.setChecked(lista.get(position).Selecionado());
        holder.edit.setText(Double.toString((lista.get(position).getValor())));

        return view;
    }

}

答案 2 :(得分:0)

那是怎么回事?

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    textStrings = new String[]{"I'm Bob", "I'm Alice"};
    checkedArray = new boolean[textStrings.length];

    final ListView lv = (ListView) findViewById(R.id.mylist);
    lv.setAdapter(new MyBaseAdapter(this, textStrings, checkedArray));
}

private String[] textStrings;
private boolean[] checkedArray;

private class MyBaseAdapter extends BaseAdapter {

    private LayoutInflater pInflater;
    private Holder pHolder;
    private String[] pTextStrings;
    private boolean[] pCheckedArray;
    private Context pContext;

    public MyBaseAdapter(Context context, String[] textStrings,
            boolean[] checkedArray) {
        this.pContext = context;
        this.pTextStrings = textStrings;
        this.pCheckedArray = checkedArray;
        this.pInflater = (LayoutInflater) context
                .getSystemService(Service.LAYOUT_INFLATER_SERVICE);

        makeAllFalse(pCheckedArray);

    }
    private void makeAllFalse(boolean[] pCheckedArray2) {
        for (Boolean b : pCheckedArray2) {
            b = false;
        }

    }
    @Override
    public int getCount() {
        return pTextStrings.length;
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        convertView = this.pInflater.inflate(R.layout.listing, null);
        this.pHolder = new Holder();
        this.pHolder.chbox = (CheckBox) convertView
                .findViewById(R.id.chbox);
        this.pHolder.chbox.setText(pTextStrings[position]);

        final int positionItem = position;
        this.pHolder.chbox
                .setOnCheckedChangeListener(new OnCheckedChangeListener() {

                    @Override
                    public void onCheckedChanged(CompoundButton buttonView,
                            boolean isChecked) {

                        checkedArray[positionItem] = isChecked;

                        if (countChecked())
                            Toast.makeText(pContext,
                                    "All checkboxes are checked",
                                    Toast.LENGTH_SHORT).show();

                    }
                });

        convertView.setTag(this.pHolder);

        return convertView;
    }

    private boolean countChecked() {
        for (boolean b : checkedArray) {
            if (!b) {
                Log.d("xxx", "not all is checked");
                return false;
            }
        }
        Log.d("xxx", "all is checked");
        return true;

    }

    private class Holder {
        CheckBox chbox;
    }

}

}

布局首先是主要的:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Random Text Here"
        android:textSize="30sp" />

    <ListView
        android:id="@+id/mylist"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </ListView>

</LinearLayout>

这是列表布局:

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

    <CheckBox
        android:id="@+id/chbox"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="item" >
    </CheckBox>

</LinearLayout>

这只是一个例子。如果您不知道,请在我的回答下发帖。

样品:

not all clicked

  

12-09 15:53:32.290:D / xxx(620):未选中全部

enter image description here

  

12-09 15:54:04.150:D / xxx(620):全部被检查