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

时间:2019-06-12 10:30:01

标签: java android listview onitemclicklistener

我正在尝试为OnClickListener的每个项目设置一个ListView,以更新或删除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>

模型类,为简单起见,我没有粘贴getter和setters

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

这是我的适配器类


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

的活动

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

    }
}

列表视图活动的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助手类

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项目上的按钮进行更新或删除项目列表的DB中的条目。

3 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:1)

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

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

希望这会对您有所帮助。

答案 2 :(得分:0)

我已添加

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

                }
            });

它从BBDD中删除了该项目,但即使我添加了notifyDataSetChanged(),列表视图也不会改变。