简体   繁体   中英

How to create onClickListener for each item of ListView

I am trying to set an OnClickListener to each item of the ListView to update or erase each item from SQLite database

list item layout

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="10dp"
    android:background="@color/grisFondo"
    android:padding="10dp">

    <ImageView
        android:id="@+id/imagencoche"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        tools:srcCompat="@tools:sample/avatars" />

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

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="center"
            android:orientation="horizontal">

            <TextView
                android:id="@+id/nombreCoche"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:gravity="center"
                android:text="TextView" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="bottom"
            android:orientation="horizontal">

            <Button
                android:id="@+id/button"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="Button" />

            <Button
                android:id="@+id/button4"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="Button"
                android:onclick="guardarCordenadas"/>
        </LinearLayout>

    </LinearLayout>

</LinearLayout>

Model class, I haven't pasted the getter & setters for simplicity

public class Coche {


    int id;
    float longitud;
    float latitud;
    Bitmap foto;
    String nombre;

    public Coche(Bitmap foto, String nombre) {

        this.foto = foto;
        this.nombre = nombre;
    }

    public Coche(int id, float longitud, float latitud, Bitmap foto, String nombre) {
        this.id = id;
        this.longitud = longitud;
        this.latitud = latitud;
        this.foto = foto;
        this.nombre = nombre;
    }

This is my adapter class


public class MiAdaptador extends BaseAdapter {

    private Context context;
    private int layout;
    private ArrayList<Coche>lista;

    public MiAdaptador(Context context, int layout, ArrayList<Coche> lista) {
        this.context = context;
        this.layout = layout;
        this.lista = lista;
    }

    @Override
    public int getCount() {
        return lista.size();
    }

    @Override
    public Object getItem(int position) {
        return lista.get(position);
    }

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

    private class ViewHolder{
        ImageView imageView;
        TextView nom;
    }

    @Override
    public View getView(int position, View view, ViewGroup parent) {
        View fila=view;
        ViewHolder holder=new ViewHolder();


        if(fila==null)
        {
            LayoutInflater inflater=(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            fila=inflater.inflate(layout,null);
            holder.imageView=fila.findViewById(R.id.imagencoche);
            holder.nom=fila.findViewById(R.id.nombreCoche);
            fila.setTag(holder);
        }
        else{
            holder=(ViewHolder)fila.getTag();

        }
        Coche coche=lista.get(position);


        holder.nom.setText(coche.getNombre());
        holder.imageView.setImageBitmap(coche.getFoto());

                return fila;
    }
}

The activity where I display the ListView


public class TodosLosCoches extends  AppCompatActivity{

    ArrayList<Coche> lista;
    ListView listview;
    MiAdaptador adapter=null;

    ImageView imageviewicon;

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


        //setListAdapter(new MiAdaptador(this,lista));

        listview=findViewById(R.id.list);
        MyOpenHelper db=new MyOpenHelper(this);
        lista=db.selectCoches();

        adapter=new MiAdaptador(this, R.layout.itemcoche,lista);
        listview.setAdapter(adapter);
        adapter.notifyDataSetChanged();

    }
}

the xml of the activity for the listview

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

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

        <Button
            android:id="@+id/button6"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Button" />

        <Button
            android:id="@+id/button7"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Button" />
    </LinearLayout>

    <ListView

        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:dividerHeight="5dp" />
</LinearLayout>

This is the SQLite helper class

public class MyOpenHelper extends SQLiteOpenHelper {

    public static final int DATABASE_VERSION = 1;
    public static final String DATABASE_NAME = "BuscaCoches.db";
    public static final String CREAR_TUSU = "CREATE TABLE usuarios (_id INTEGER PRIMARY KEY AUTOINCREMENT, nombre TEXT, pwd TEXT)";
    public static final String CREAR_TCOCHE = "CREATE TABLE coches(_id INTEGER PRIMARY KEY AUTOINCREMENT,nombre TEXT, longitud REAL, latitud REAL,foto BLOB)";
    public MiAdaptador adapter;


    public MyOpenHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);

    }



    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREAR_TUSU);
        db.execSQL(CREAR_TCOCHE);

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }




    //metodo para seleccionar el usuario de la BBDD al solo haber un usuario no usamos un bucle

    public Usuario getUsu()
    {
        Usuario  usu=null;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor c = db.rawQuery("SELECT nombre,pwd,_id FROM usuarios ", null);
        if (c.moveToFirst()){

               //recogemos valores
                String nom = c.getString(0);
                int pwd = c.getInt(1);
                int id=c.getInt(2);

                //creamos usuario a devolver
               usu = new Usuario(id,nom,pwd);



        }
        c.close();
        db.close();
        return usu;
    }
    public boolean hayCoches()
    {

        SQLiteDatabase db=this.getWritableDatabase();
        Cursor c =db.rawQuery("SELECT nombre from coches", null);
        if(c.getCount()>0)
        {
            c.close();
            return true;
        }

        c.close();
        return false;
    }


    public void setUsu(Usuario u)
    {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues cv =new ContentValues();
        cv.put("nombre",u.getNombre());
        cv.put("pwd",u.getPwd());

        db.insert("usuarios", null, cv);
        db.close();


    }
    public ArrayList<Coche> selectCoches(){
        ArrayList<Coche> lista =new ArrayList<Coche>();

        SQLiteDatabase db=this.getReadableDatabase();
        Cursor c =db.rawQuery("SELECT nombre, foto, longitud, latitud,_id from coches", null);

        if (c.moveToFirst()){
            do {
                //recogemos valores
                String nom = c.getString(0);
                byte[] foto = c.getBlob(1);
                float longitud = c.getFloat(2);
                float latitud = c.getFloat(3);
                int id = c.getInt(4);
                Coche coche = new Coche(id, longitud, latitud, DbBitMapUtility.getImage(foto), nom);
                lista.add(coche);


            }while(c.moveToNext());


        }

        return lista;

    }

    public void setCar(Coche c )
    {
        SQLiteDatabase db= this.getWritableDatabase();
        ContentValues cv =new ContentValues();

        cv.put("nombre",c.getNombre());
        cv.put("foto",DbBitMapUtility.getBytes(c.getFoto()));

        db.insert("coches", null, cv);
        db.close();
    }

    public static void borrar(Context c)
    {
        c.deleteDatabase(DATABASE_NAME);
    }

}

I cant achieve to make the buttons on the ListView items to update or erase the entry in the DB of the item list.

The easiest way to set click event on each item is

 yourListView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
                // here you can do what you want based on the position or id
            }
        });

In your adapter, inside getView() method set clickListener holder.nom

holder.nom.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // do something
        }
    });

Hope this will help you.

i have added

 holder.borrar.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    MyOpenHelper db=new MyOpenHelper(context);
                    db.borrarCoche(position+"");
                    notifyDataSetChanged();

                }
            });

it erases the item from the BBDD but the Listview does not change, even when i added notifyDataSetChanged();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM