Pregunta

Tengo un ListView. Cuando se toca un elemento en el ListView, se carga una vista secundaria. Quiero asignar un ID para cada fila del ListView, para que pueda pasar esa identificación junto a la subvista. ¿Cómo se asigna un identificador específico para cada fila de la ListView?

Esta es la forma en que actualmente estoy cargando al ListView:

setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, mArrayList));
¿Fue útil?

Solución

Así es como he resuelto el problema. Tengo los employee_ids y employee_names de la base de datos local SQLite, entonces crearon un ArrayList de employeeNamesArray y un ArrayList de employeeIdArray al mismo tiempo. Por lo tanto, la employeeIdArray [0] coincidiría con employeeNameArray [0], employeeIdArray [1] se correspondería con employeeNameArray [1], etc.

Una vez se han creado los ArrayLists, Alimenté employeeNameArray en el ListView.

Más tarde, en onListItemClick, I retreive la posición de la fila ListView seleccionado. Esta 'posición' se corrospond a la posición en las ArrayLists - por lo tanto, si selecciono la primera fila de la ListView, la posición será cero, y employeeNameArray [0] partidos employeeIdArray [0]. Agarro la entrada de coroloating employeeIdArray y empuje que a la siguiente actividad mediante el uso de putExtra.

public class MyFirstDatabase extends ListActivity {
    ArrayList<String> employeeIdArray = new ArrayList<String>(); // List of EmployeeIDs

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);                                                           

        // Open the database
        SQLiteDatabase db;
        db = openOrCreateDatabase("mydb.db",SQLiteDatabase.CREATE_IF_NECESSARY, null);
        db.setVersion(1);
        db.setLocale(Locale.getDefault());
        db.setLockingEnabled(true);

        // Query the database
        Cursor cur = db.query("employee", null, null, null, null, null, "employee_lastname"); 

        cur.moveToFirst(); // move to the begin of the db results       

        ArrayList<String> employeeNameArray = new ArrayList<String>(); // Initialize mArrayList


        while (cur.isAfterLast() == false) {
            employeeNameArray.add(cur.getString(1)); // add the employee name to the nameArray
            employeeIdArray.add(cur.getString(0)); // add the employee id to the idArray
            cur.moveToNext(); // move to the next result set in the cursor
        } 

        cur.close(); // close the cursor


        // put the nameArray into the ListView  
        setListAdapter(new ArrayAdapter<String>(this,R.layout.list_item,employeeNameArray));          
        ListView lv = getListView();  
        lv.setTextFilterEnabled(true);
    }


    protected void onListItemClick(ListView l, View v, final int position, long id) { 
        super.onListItemClick(l, v, position, id);                
        Intent myIntent = new Intent(this, SubView.class); // when a row is tapped, load SubView.class

        Integer selectionID = Integer.parseInt(employeeIdArray.get(position)); // get the value from employeIdArray which corrosponds to the 'position' of the selected row
        myIntent.putExtra("RowID", selectionID); // add selectionID to the Intent   

        startActivityForResult(myIntent, 0); // display SubView.class  

    } 
}

Otros consejos

Hola Chris ya tiene el id posición en su vista de lista, implementar la función onListItemClick ().

    protected void onListItemClick(ListView l, View v, final int position, long id) {
      super.onListItemClick(l, v, position, id);               
      Toast.makeText(this,  "my id to pass along the subview is " + position,Toast.LENGTH_LONG).show();

   }

Si desea assing su propio uso Identificación del setTag ()

v.setTag("myownID"+position);

No se puede hacer eso con un estándar ArrayAdapter Usted necesidad de extender el ArrayAdapter y sobrescribir el GetItemID () método y tal vez también la hasStableIds () método.

A continuación, tiene que devolver cierto en el método hasStableIds y generar su ID para el elemento en la posición que se le da a su método de GetItemID.

Después de pasar horas en esto, de esta manera más fácil que encontré fue para anular Bindview del adaptador y establecer un valor de etiqueta que contiene _id de la fila en el tema - en mi caso, se trataba de un botón en la fila ListView

SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
        R.layout.note, cursor, fromColumns, toViews, 0) {

    @Override
    // add the _id field value to the button's tag
    public void bindView(View view, Context context, Cursor cursor) {
        super.bindView(view, context, cursor);
        Integer index = cursor.getColumnIndex("_id");
        Integer row_id = cursor.getInt(index);
        Button button = (Button) view.findViewById(R.id.button_delete_record);
        button.setTag(row_id);
    }
};
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top