不显示自定义ListView

时间:2013-05-21 00:47:40

标签: java android android-listview

按照一些教程,我设法制作了一个自定义列表。

但整个屏幕只是一个列表

现在想把列表放在表格下面。并使整个屏幕与列表一起滚动(参见列表中的最后一项,表格需要上升)

日志(Toasty)说该项目已添加,但没有任何内容。我不知道问题是我的添加方式,还是我尝试显示的方式

这是我的布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="#ffffff"
    android:fillViewport="true"
    android:padding="5dp" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical" >

            <TextView
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="@string/cliente" />

            <EditText
                android:id="@+id/venda_form_cliente"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:cursorVisible="false"
                android:focusable="false"
                android:hint="@string/selecione_um_cliente" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical" >

            <TextView
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="@string/produto" />

            <EditText
                android:id="@+id/venda_form_prod"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:cursorVisible="false"
                android:focusable="false"
                android:hint="@string/selecione_um_produto" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal" >

            <LinearLayout
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:orientation="vertical" >

                <TextView
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:text="@string/quantidade" />

                <EditText
                    android:id="@+id/venda_form_qtd"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:inputType="numberDecimal"
                    android:selectAllOnFocus="true"
                    android:text="@string/um" />
            </LinearLayout>

            <LinearLayout
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:orientation="vertical" >

                <TextView
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:text="@string/valor" />

                <EditText
                    android:id="@+id/venda_form_valor"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:cursorVisible="false"
                    android:focusable="false"
                    android:inputType="none" />
            </LinearLayout>
        </LinearLayout>

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal" >

            <LinearLayout
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:orientation="vertical" >

                <TextView
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:text="@string/desconto" />

                <EditText
                    android:id="@+id/venda_form_desc"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:inputType="numberDecimal"
                    android:selectAllOnFocus="true"
                    android:text="@string/zero" />
            </LinearLayout>

            <LinearLayout
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:orientation="vertical" >

                <TextView
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:text="@string/subtotal" />

                <EditText
                    android:id="@+id/venda_form_subtotal"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:cursorVisible="false"
                    android:focusable="false"
                    android:inputType="none" />
            </LinearLayout>
        </LinearLayout>

        <Button
            android:id="@+id/venda_form_btn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:padding="10dp"
            android:text="@string/adicionar" />

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" >

            <ListView
                android:id="@android:id/list"
                android:layout_width="fill_parent"
                android:layout_height="0dp"
                android:layout_weight="1"
                android:scrollbars="none" >
            </ListView>
        </LinearLayout>
    </LinearLayout>

</LinearLayout>

我的活动

public class VendaFormActivity extends Activity {

    private Cliente cliente;
//  private Spinner condicaoSelect;
    private Produto produto;
    private TextWatcher somar;
    private ItemVenda itemVenda;
    private ListaAdapter listaAdapter;
    private EditText inputQuantidade;
    private EditText inputDesconto;
    private EditText inputSubTotal;
    private EditText inputProduto;
    private EditText inputValor;

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

        inputProduto = ((EditText) findViewById(R.id.venda_form_prod));
        inputValor = ((EditText) findViewById(R.id.venda_form_valor));

        ((EditText) findViewById(R.id.venda_form_cliente)).setOnClickListener(new ClickListener(this, ClienteActivity.class, MainActivity.REQUEST_CLIENTE));
        inputProduto.setOnClickListener(new ClickListener(this, ProdutoActivity.class, MainActivity.REQUEST_PRODUTO));

        //condicaoSelect = (Spinner) findViewById(R.id.venda_form_condicao);
        //new CondicaoHelper(this).popular(condicaoSelect);

        bindCamposValores();
        fazerLista();
        bindBtnAdd();
    }

    private void limparCamposValores() {
        inputDesconto.setText("0.00");
        inputQuantidade.setText("1");
        inputSubTotal.getText().clear();
        inputProduto.getText().clear();
    }

    private void bindBtnAdd() {
        ((Button) findViewById(R.id.venda_form_btn)).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                try{
                    Double quantidade = Double.parseDouble( inputQuantidade.getText().toString() );
                    Double desconto = Double.parseDouble( inputDesconto.getText().toString() );

                    itemVenda = new ItemVenda();
                    itemVenda.setDesconto(desconto);
                    itemVenda.setProduto(produto);
                    itemVenda.setQuantidade(quantidade);

                    listaAdapter.setNotifyOnChange(true);
                    listaAdapter.getItens().add(itemVenda);
                    listaAdapter.notifyDataSetChanged();

                    Toast.makeText(getApplication(), "Foi", Toast.LENGTH_SHORT).show();

                    limparCamposValores();
                } catch (Exception e) {
                    Toast.makeText(getApplication(), "Invalido", Toast.LENGTH_SHORT).show();
                    // NPE no produto
                    // NumberFormat nos valores
                }
            }
        });
    }

    private void fazerLista() {
        listaAdapter = new ListaAdapter(getApplicationContext());
        ((ListView) findViewById(android.R.id.list)).setAdapter(listaAdapter);
    }

    static class ViewHolder {
        protected TextView descricao;
        protected TextView codigo;
        protected TextView ean;
        protected TextView referencia;
        protected TextView quantidade;
        protected TextView valor_unit;
        protected TextView valor_item;
    }

    private class ListaAdapter extends ArrayAdapter<ItemVenda>{
        private final Context context;
        private final List<ItemVenda> itens;

        public ListaAdapter(Context context) {
            super(context, R.layout.produto_list);
            this.context = context;
            this.itens = new LinkedList<ItemVenda>();
        }
        public ListaAdapter(Context context, List<ItemVenda> itens) {
            super(context, R.layout.produto_list, itens);
            this.context = context;
            this.itens = itens;
        }

        public List<ItemVenda> getItens() {
            return itens;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = null;
            if (convertView == null) {
                LayoutInflater inflator = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                view = inflator.inflate(R.layout.produto_list_item, null);

                final ViewHolder viewHolder = new ViewHolder();
                viewHolder.descricao = (TextView) view.findViewById(R.id.descricao);
                viewHolder.codigo = (TextView) view.findViewById(R.id.codigo);
                viewHolder.ean = (TextView) view.findViewById(R.id.ean);
                viewHolder.referencia = (TextView) view.findViewById(R.id.referencia);
                viewHolder.quantidade = (TextView) view.findViewById(R.id.quantidade);
                viewHolder.valor_unit = (TextView) view.findViewById(R.id.valor_unit);
                viewHolder.valor_item = (TextView) view.findViewById(R.id.valor_item);

                view.setTag(viewHolder);
            } else {
                  view = convertView;
            }

            ViewHolder holder = (ViewHolder) view.getTag();

            ItemVenda item = itens.get(position);
            holder.descricao.setText(item.getProduto().getNome());
            holder.codigo.setText(item.getProduto().getCodigo());
            holder.ean.setText(item.getProduto().getEan());
            holder.referencia.setText(item.getProduto().getReferencia());
            holder.quantidade.setText(item.getQuantidade().toString());
            holder.valor_unit.setText(item.getProduto().getPreco().toString());
            holder.valor_item.setText(item.getSubTotal().toString());

            return view;
        }

    }

    private void bindCamposValores() {
        inputQuantidade = ((EditText) findViewById(R.id.venda_form_qtd));
        inputDesconto = ((EditText) findViewById(R.id.venda_form_desc));
        inputSubTotal = ((EditText) findViewById(R.id.venda_form_subtotal));

        somar = new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { }

            @Override
            public void afterTextChanged(Editable arg0) {
                Double sub = 0.0;

                try{
                    itemVenda = new ItemVenda();
                    itemVenda.setQuantidade(Double.parseDouble(inputQuantidade.getText().toString()));
                    itemVenda.setDesconto(Double.parseDouble(inputDesconto.getText().toString()));
                    itemVenda.setProduto(produto);

                    sub = itemVenda.getSubTotal();
                } catch (Exception e) {
                    // algum campo não é numero/está vazio
                }

                inputSubTotal.setText(""+sub);
            }
        };

        // Se mudar o valor
        inputQuantidade.addTextChangedListener(somar);
        inputDesconto.addTextChangedListener(somar);

        // quando sair do campo
        inputQuantidade.setOnFocusChangeListener(new Focus("1"));
        inputDesconto.setOnFocusChangeListener(new Focus("0.00"));
    }

    private class Focus implements OnFocusChangeListener {

        private final String padrao;

        public Focus(String padrao){
            this.padrao = padrao;
        }

        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if(!hasFocus){

                Editable text = ((EditText) v).getText();
                if(null == text || "".equals(text.toString())){
                    text.append(padrao);
                }
            }
        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_venda_form, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
            case R.id.menu_copiar:
                copiar();
                return true;

            case R.id.menu_simulacao:
                simulacao();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    private void copiar() {
        Toast.makeText(getApplication(), "Nada ainda", Toast.LENGTH_SHORT).show();

    }

    private void simulacao() {
        Intent intent = new Intent(getApplicationContext(), SimulacaoPagtoActivity.class);
        startActivityForResult(intent, MainActivity.REQUEST_SIMULACAO);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        if (requestCode == MainActivity.REQUEST_CLIENTE) {

            if (resultCode == RESULT_OK) {
                cliente = (Cliente) intent.getSerializableExtra(MainActivity.RESULT_MODEL_LIST);
                ((EditText) findViewById(R.id.venda_form_cliente)).setText(cliente.getNome());
            }

        } else if (requestCode == MainActivity.REQUEST_PRODUTO) {

            if (resultCode == RESULT_OK) {
                produto = (Produto) intent.getSerializableExtra(MainActivity.RESULT_MODEL_LIST);
                inputProduto.setText(produto.getNome());
                inputValor.setText(""+produto.getPreco());
                somar.afterTextChanged(null);
            }

        } else if(requestCode == MainActivity.REQUEST_SIMULACAO){
            // o que fazer quando voltar da simulação ?
        }
    }

}

最后,我的项目布局

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

    <TextView
        android:id="@+id/descricao"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textColor="#333"
        android:textSize="16sp"
        android:textStyle="bold" />

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <TextView
            android:id="@+id/codigo"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="CODIGO" />

        <TextView
            android:id="@+id/ean"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="EAN" />

        <TextView
            android:id="@+id/referencia"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="REFERENCIA" />

    </LinearLayout>
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <TextView
            android:id="@+id/quantidade"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="QUANT." />

        <TextView
            android:id="@+id/valor_unit"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="VLR UNIT" />

        <TextView
            android:id="@+id/valor_item"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="VLR ITEM" />

    </LinearLayout>

</LinearLayout>

更新

当我在列表中添加项目时,不会显示任何内容。但是在我单击一个TextEdit和虚拟键盘后,键入一些值后,我关闭键盘,然后调用adapter.getView()并显示列表

3 个答案:

答案 0 :(得分:4)

我想我发现了你的问题。不应该使用以下代码:

((ListView) findViewById(android.R.id.list)).setAdapter(listaAdapter);

是:

((ListView) findViewById(R.id.list)).setAdapter(listaAdapter);

代替?

您正在尝试查找默认的Android视图,而不是您创建的视图,这意味着您实际上并未为ListView设置适配器。

答案 1 :(得分:1)

我不确定,但如果您希望列表可以使用活动滚动,则应使用ScrollView,然后检查是否滚动列表或视图本身。试试吧

如果项目实际上已添加到列表中,您还可以尝试使用调试器查看。我希望你会发现错误。

答案 2 :(得分:0)

找到解决方案

1)适配器有2个构造函数,但只有1个List<ItemVenda> itens,并且不会调用它。 我修好了。

2)要在列表中添加项目,我需要调用adapter.add()而不是adapter.getItens()。add()`。我认为这会引发其他方法。

3)最后,要获取滚动列表,并在屏幕上应用滚动,我需要增加列表的大小。然后我重写方法adapter.add(),并计算列表的新高度,并在android:scrollbars="none"上添加ListView

感谢所有人,特别是@Marek