Edit item within Listview

Asked

Viewed 4,475 times

1

Hello. I am working on a code that loads items inside the Listview through a Adapter. Within each item (item_list.xml), I inserted two buttons being one to delete the item and another to edit. The method that deletes the item is working perfectly but I am not able to implement the method to edit them. Could someone help me?

Below classes relevant to the use of the information mentioned above:

Adapterlistview

package com.example.aulasandroid.aulas_android_listviewactions;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.ArrayList;

/**
* Created by lmontanhine on 11/2/2015.
*/
public class AdapterListView extends BaseAdapter {

private LayoutInflater mInflater;
private ArrayList<ItemListView> itens;

public AdapterListView(Context context, ArrayList<ItemListView> itens) {
    //Itens que preencheram o listview
    this.itens = itens;
    //responsavel por pegar o Layout do item.
    mInflater = LayoutInflater.from(context);
}

/**
 * Retorna a quantidade de itens
 *
 * @return
 */
public int getCount() {
    return itens.size();
}

/**
 * Retorna o item de acordo com a posicao dele na tela.
 *
 * @param position
 * @return
 */
public ItemListView getItem(int position) {
    return itens.get(position);
}

/**
 * Sem implementação
 *
 * @param position
 * @return
 */
public long getItemId(int position) {
    return position;
}

public View getView(int position, View view, ViewGroup parent) {
    //Pega o item de acordo com a posção.
    ItemListView item = itens.get(position);
    //infla o layout para podermos preencher os dados
    view = mInflater.inflate(R.layout.item_list, null);

    //atraves do layout pego pelo LayoutInflater, pegamos cada id relacionado
    //ao item e definimos as informações.
    ((TextView) view.findViewById(R.id.text)).setText(item.getTexto());
    ((ImageView) view.findViewById(R.id.imagemview)).setImageResource(item.getIconeRid());
    ((Button) view.findViewById(R.id.btnDelete)).setTag(position);
    ((Button) view.findViewById(R.id.btnEdit)).setTag(item);

    return view;
}
public void removeItem(int positionToRemove){
    itens.remove(positionToRemove);
    notifyDataSetChanged();
}

public void updateItens(ArrayList<ItemListView> itens) {
    self.itens = itens;
    notifyDataSetChanged();
}

}

Mainactivity

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;


public class MainActivity extends Activity implements AdapterView.OnItemClickListener {

private ListView listView;
private AdapterListView adapterListView;
private ArrayList<ItemListView> itens;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //carrega o layout onde contem o ListView
    setContentView(R.layout.activity_main);

    //Pega a referencia do ListView
    listView = (ListView) findViewById(R.id.list);
    //Define o Listener quando alguem clicar no item.
    listView.setOnItemClickListener(this);

    createListView();


}

private void createListView() {
    //Criamos nossa lista que preenchera o ListView
    itens = new ArrayList<ItemListView>();
    ItemListView item1 = new ItemListView("Felpudo", R.drawable.felpudo);
    ItemListView item2 = new ItemListView("Felpudão", R.drawable.felpudo1);
    ItemListView item3 = new ItemListView("Felpudinho", R.drawable.felpudo2);

    itens.add(item1);
    itens.add(item2);
    itens.add(item3);

    //Cria o adapter
    adapterListView = new AdapterListView(this, itens);

    //Define o Adapter
    listView.setAdapter(adapterListView);
    //Cor quando a lista é selecionada para ralagem.
    listView.setCacheColorHint(Color.TRANSPARENT);
}

public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
    //Pega o item que foi selecionado.
    ItemListView item = adapterListView.getItem(arg2);
    //Demostração
    Toast.makeText(this, "Você Clicou em: " + item.getTexto(), Toast.LENGTH_LONG).show();
}

public void deletaItem(View v) {
    adapterListView.removeItem((Integer) v.getTag());
}

public void editaItem(View v){
    onItemClick();
}

public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
    //Posição na lista
    final int selecionado = arg2;

    //Pega o item que foi selecionado.
    ItemListView item = adapterListView.getItem(arg2);

    final AlertDialog.Builder alert = new AlertDialog.Builder(this);
    final EditText input = new EditText(this);
    input.setText(item.getTexto());
    alert.setView(input);
    alert.setPositiveButton("Alterar", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
            String value = input.getText().toString().trim();
            item.setTexto(value);

            itens.set(selecionado, item);

            adapterListView.updateItens(itens);
        }
    });

    alert.setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
            dialog.cancel();
        }
    });

    alert.show();
}

}

Itemlistview

package com.example.aulasandroid.aulas_android_listviewactions;

/**
* Created by lmontanhine on 11/2/2015.
*/
public class ItemListView {

private String texto;
private String nome;
private int iconeRid;

public ItemListView() {
}

public ItemListView(String texto, int iconeRid) {
    this.texto = texto;
    this.iconeRid = iconeRid;
}

public int getIconeRid() {
    return iconeRid;
}

public void setIconeRid(int iconeRid) {
    this.iconeRid = iconeRid;
}

public String getTexto() {
    return texto;
}

public void setTexto(String texto) {
    this.texto = texto;
}

public String getNome(String nome) {
    return nome;
}

public void setNome (String nome){
    this.nome = nome;
}

}

item_list.xml (contains information of the buttons that make the actions to delete and edit the list items)

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    android:padding="5sp">
    <ImageView
        android:id="@+id/imagemview"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        />
    <Button
        android:id="@+id/btnEdit"
        android:layout_width="80dp"
        android:layout_height="40dp"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:focusable="false"
        android:focusableInTouchMode="false"
        android:text="Editar"
        android:textColor="#FFFFFF"
        android:onClick="editaItem"/>

    <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:focusable="false"
        android:focusableInTouchMode="false"
        android:text="Deletar"
        android:textColor="#FFFFFF"
        android:onClick="deletaItem"/>
    <TextView
        android:id="@+id/text"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_centerVertical="true"
        android:layout_marginLeft="115sp"
        android:gravity="center_vertical"
        android:textColor="#FF000000"
        />

</RelativeLayout>
</RelativeLayout>
  • In what sense do you intend to carry out this edition? It is an edition inline, open another Activity or something specific? That you did not specify, it would be good this detail to have a correct direction.

  • It would edit the list item, actually just the name. I imagine that it is necessary to create a new layout Activity to allow the user to enter the name that will be updated and after that, update the item. @Paulorodrigues

1 answer

2


I’m guessing you created a class Itemlistview that has some attribute that defines the text of this line in your list, right? As it does not seem that you are persisting this data (as hard coded), this would be the simplest solution, unless you need to persist this data somewhere, then the method would be different.

Since it’s just a string change, I didn’t opt for a Activity to accomplish something very simple, I believe a dialog window will solve this issue. Then, at the click of the button, you will have something like this:

public void editaItem(View v) {
    //Posição na lista
    final int selecionado = (Integer) v.getTag();

    //Pega o item que foi selecionado.
    final ItemListView item = adapterListView.getItem(selecionado);

    final AlertDialog.Builder alert = new AlertDialog.Builder(this);
    final EditText input = new EditText(this);
    input.setText(item.getTexto());
    alert.setView(input);
    alert.setPositiveButton("Alterar", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
            String value = input.getText().toString().trim();
            item.setTexto(value);

            itens.set(selecionado, item);

            adapterListView.updateItens(itens);
        }
    });

    alert.setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
            dialog.cancel();
        }
    });

    alert.show();
}

Note that in your Adapter I needed to create a method updateItens because you will need to change the items in it again and inform that the data has been changed, thus:

public void updateItens(ArrayList<ItemListView> itens) {
    this.itens = itens;
    notifyDataSetChanged();
}

And the tag of this button, there on your Adapter, now needs the position and not the item:

((Button) view.findViewById(R.id.btnEdit)).setTag(position);

It’s something like that, see if that’s what you look for and say.

  • What is arg2 in itens.set(arg2, item);

  • Is the index of the item in the list, indicated in the method onItemClick, where I suggested adding this code.

  • I updated my question and entered my class Itemlistview with getNome and setNome but for that, I needed to create the variable name and I didn’t see any place of your code that used it. I was a little lost in how it would look my Mainactivity with the change suggested by you in the first block. Can you edit considering my Main class I put here in the question by inserting the part suggested by you? Thanks for the help @Paulorodrigues

  • @Luizhenriqueugliano changed my answer with my suggestion of the method onItemClick. Actually I had suggested this name attribute but then edited because I saw that you already had the property text, then as in your XML, what you have to relevant is text and image, it is only this attribute that changes.

  • @Paulorodrigues updated the Mainactivity and Adapterlistview according to your suggestions but I still have the following mistakes: In class Adapterlistview, is not recognizing the "self", line self.itens = itens. In the Mainactivity class I am unable to call the onItemClick method in the method I created to edit my button public void editaItem. The "item" variable is asking to be declared in the onItemClick method. That’s right?

  • @Luizhenriqueugliano ops, sorry, actually it is this. I swabbed the languages :D

  • @Paulorodrigues In the Mainactivity class I am not able to call the onItemClick method in the method I created to edit the item through my button public void editaItem. The "item" variable is asking to be declared in the onItemClick method. That’s right?

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.