Erro em aplicação Android - Erro no ListView com botões

  • Respostas:0
jrxxjr
  • Posts no fórum: 1

26/07/2020, 22:17:13 via Web

Sou iniciante em Android, e fiz uma pequena aplicação Android de teste, usando Java, para aprender a utilizar um ListView com botões, e tive um problema. Os botões não funcionam direito, as vezes eu clico em cima do Edit, ele muda a mensagem para clicado, "Edit", confirmando que eu cliquei ai. Mas tem vezes que eu clico no botão Delete, e depois no botão Edit, e o texto não é mudado, ou seja o evento click não funcionou, se eu coloco um break point, no código-fonte, onde está entrando no evento setOnItemClickListener. Mas a mensagem exibida, não está correta.
E tem um outro erro, de funcionamento do AlertDialog, da mensagem de confirmação de deleção.
O código-fonte está abaixo.
Por favor, alguém poderia me ajudar ?

Obs: Nos arquivos de layout, no xml não está as urls completas, o site aqui tem como regra de segurança, não permitir urls externas, por favor corrigir.


classe AgendaActivity.java

package com.test.android.view;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.test.android.model.Agenda;
import com.test.android.util.Util;

public class AgendaActivity extends AppCompatActivity {

ListView listview;
MyArrayAdapter agendaArrayAdapter;
ArrayList<AgendaTo> agendaArray = new ArrayList<AgendaTo>();

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

    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");

    agendaArray.add(new AgendaTo(sdf.format(new Date()), Util.fillSpaces("Nick", 50)));
    agendaArray.add(new AgendaTo(sdf.format(new Date()), Util.fillSpaces("John", 50)));
    agendaArray.add(new AgendaTo(sdf.format(new Date()), Util.fillSpaces("Anthony", 50)));
    agendaArray.add(new AgendaTo(sdf.format(new Date()), Util.fillSpaces("James", 50)));
    agendaArray.add(new AgendaTo(sdf.format(new Date()), Util.fillSpaces("Jack", 50)));
    agendaArray.add(new AgendaTo(sdf.format(new Date()), Util.fillSpaces("Jeremy", 50)));
    agendaArray.add(new AgendaTo(sdf.format(new Date()),Util.fillSpaces("Long", 50)));

    agendaArrayAdapter = new MyArrayAdapter(AgendaActivity.this, R.layout.list_item, agendaArray);
    listview = (ListView) findViewById(R.id.listView);
    listview.setItemsCanFocus(false);
    listview.setAdapter(agendaArrayAdapter);

    listview.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View v,
                                final int position, long id) {

            Toast.makeText(AgendaActivity.this,
                    "List Item Clicked:" + position, Toast.LENGTH_LONG)
                    .show();
        }
    });

}

}


classe MyArrayAdapter

package com.test.android.view;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.text.SimpleDateFormat;
import java.util.ArrayList;

public class MyArrayAdapter extends ArrayAdapter {

Context context;
int layoutResourceId;
ArrayList<AgendaTo> agendas = new ArrayList<AgendaTo>();

public MyArrayAdapter(Context context, int layoutResourceId,
                      ArrayList<AgendaTo> agendas) {
    super(context, layoutResourceId, agendas);
    this.layoutResourceId = layoutResourceId;
    this.context = context;
    this.agendas = agendas;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View item = convertView;
    AgendaWrapper agendaWrapper = null;

    if (item == null) {
        LayoutInflater inflater = ((Activity) context).getLayoutInflater();
        item = inflater.inflate(layoutResourceId, parent, false);
        agendaWrapper = new AgendaWrapper();
        agendaWrapper.nome = (TextView) item.findViewById(R.id.textNome);
        agendaWrapper.data = (TextView) item.findViewById(R.id.textData);
        agendaWrapper.edit = (Button) item.findViewById(R.id.btnEdit);
        agendaWrapper.delete = (Button) item.findViewById(R.id.btnDelete);
        item.setTag(agendaWrapper);
    } else {
        agendaWrapper = (AgendaWrapper) item.getTag();
    }

    AgendaTo agenda = agendas.get(position);
    agendaWrapper.nome.setText(agenda.getNome());
    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
    agendaWrapper.data.setText(sdf.format(agenda.getData()));        

    agendaWrapper.edit.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            Toast.makeText(context, "Edit", Toast.LENGTH_LONG).show();
        }
    });

    final int absolutePsition = position;
    final AgendaWrapper itemDelete = agendaWrapper;
    final ViewGroup viewGroup = parent;

    agendaWrapper.delete.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            Toast.makeText(context, "Delete " + absolutePsition, Toast.LENGTH_LONG).show();
            AlertDialog diaBox = AskOption(itemDelete, absolutePsition, viewGroup);
            diaBox.show();

        }
    });

    return item;

}

private AlertDialog AskOption(AgendaWrapper agendaWrapper, int position, final ViewGroup viewGroup) {
    final int deletePosition = position;
    AlertDialog myQuittingDialogBox = new AlertDialog.Builder(context)

            .setTitle("Delete")
            .setMessage("Do you want to Delete")

            .setPositiveButton("Delete", new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int whichButton) {
                    agendas.remove(deletePosition);
                    refreshListView(agendas, viewGroup);
                    dialog.dismiss();
                }

                private void refreshListView(final ArrayList<AgendaTo> agendas, final ViewGroup viewGroup) {
                    final MyArrayAdapter myArrayAdapter = new MyArrayAdapter(context, R.layout.list_item, agendas);
                    final LayoutInflater inflater = ((Activity) context).getLayoutInflater();
                    final View view = inflater.inflate(layoutResourceId, viewGroup, false);
                    final ListView listview = (ListView) view.findViewById(R.id.listView);
                    listview.setAdapter(myArrayAdapter);
                }

            })
            .setNegativeButton("cancel", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            })
            .create();

    return myQuittingDialogBox;
}


static class AgendaWrapper {
    TextView nome;
    TextView data;
    Button edit;
    Button delete;
}

}


arquivo list_item.xml

xmlns:tools="schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="4dp"
tools:context=".AgendaActivity" >

<TextView
    android:id="@+id/textNome"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:text="Nome:"
    android:width="50dp"
    android:textAppearance="?android:attr/textAppearanceLarge" />

<TextView
    android:id="@+id/textData"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/textData"
    android:layout_alignTop="@id/textNome"
    android:layout_alignRight="@id/textNome"
    android:layout_alignParentLeft="true"
    android:layout_marginTop="5dp"
    android:width="50dp"
    android:text="Data:"
    android:textAppearance="?android:attr/dateTextAppearance"
    android:textSize="16sp" />

<Button
    android:id="@+id/btnEdit"
    android:layout_width="80dp"
    android:layout_height="40dp"
    android:layout_alignParentRight="true"
    android:layout_alignParentTop="true"
    android:background="#99CC"
    android:focusable="false"
    android:focusableInTouchMode="false"
    android:text="Edit"
    android:textColor="#FFFFFF" />

<Button
    android:id="@+id/btnDelete"
    android:layout_width="80dp"
    android:layout_height="40dp"
    android:layout_alignParentRight="true"
    android:layout_below="@+id/btnEdit"
    android:layout_marginTop="3dp"
    android:background="#99CC"
    android:focusable="false"
    android:focusableInTouchMode="false"
    android:text="Delete"
    android:textColor="#FFFFFF" />


arquivo activity_agenda.xml

xmlns:tools="schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#990044"
tools:context="com.test.android.view.AgendaActivity" >

<TextView
    android:id="@+id/listLabel"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:text="Touch List"
    android:textColor="#FFFFFF"
    android:textSize="25sp" />

<ListView
    android:id="@+id/listView"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_below="@+id/listLabel"
    android:layout_marginTop="5dp"
    android:cacheColorHint="#FFFFFF" />

— alterado em 26/07/2020, 22:21:28

Seja o primeiro a responder