Как создать onClickListener для каждого элемента ListView - PullRequest
1 голос
/ 12 июня 2019

Я пытаюсь установить 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>

Модель класса, я не вставил геттер и сеттеры для простоты

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 обновить или удалить запись в БД списка элементов.

Ответы [ 3 ]

2 голосов
/ 12 июня 2019

Самый простой способ установить событие клика для каждого элемента -

 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 голос
/ 12 июня 2019

В вашем адаптере, внутри метода getView (), установите clickListener holder.nom

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

Надеюсь, это поможет вам.

0 голосов
/ 12 июня 2019

Я добавил

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

                }
            });

, он стирает элемент с BBDD, но ListView не меняется, даже когда я добавил notifyDataSetChanged ();

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...