如何为 ListView 的每个项目创建 onClickListener

How to create onClickListener for each item of ListView

我正在尝试为 ListView 的每个项目设置 OnClickListener 以更新或删除 SQLite 数据库中的每个项目

列表项布局

<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>

模型 class,为了简单起见,我没有粘贴 getter 和设置器

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;
    }

这是我的适配器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;
    }
}

我显示ListView

的activity

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();

    }
}

列表视图activity的xml

<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>

这是 SQLite 助手 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);
    }

}

我无法实现 ListView 项目上的按钮来更新或删除项目列表数据库中的条目。

在您的适配器中,在 getView() 方法内设置 clickListener holder.nom

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

希望对您有所帮助。

为每个项目设置点击事件的最简单方法是

 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
            }
        });

我已经添加了

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

                }
            });

它从 BBDD 中删除项目但列表视图没有改变,即使我添加了 notifyDataSetChanged();