Domanda

Ho un ListView. Quando un elemento sul ListView è sfruttato, carica una visualizzazione secondaria. Voglio assegnare un ID a ciascuna riga della ListView, quindi posso passare che ID insieme alla visualizzazione secondaria. Come faccio ad assegnare un ID specifico per ogni riga della ListView?

Ecco come Attualmente sto caricando il ListView:

setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, mArrayList));
È stato utile?

Soluzione

Ecco come ho risolto il problema. Ho avuto le employee_ids e employee_names dal database locale SQLite, poi ho creato un ArrayList di employeeNamesArray e un ArrayList di employeeIdArray allo stesso tempo. Così, l'employeeIdArray [0] sarebbe partita con employeeNameArray [0], employeeIdArray [1] sarebbe partita con employeeNameArray [1], ecc

Una volta che i ArrayLists sono stati creati, ho dato da mangiare employeeNameArray nella ListView.

Successivamente, nel onListItemClick, ho retreive la posizione della riga selezionata ListView. Questo 'posizione' si corrospond alla posizione in ArrayLists - così, se si seleziona la prima riga in ListView, la posizione sarà zero, e employeeNameArray [0] incontri employeeIdArray [0]. Afferro la voce coroloating da employeeIdArray e spinta che alla prossima attività utilizzando 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  

    } 
}

Altri suggerimenti

Ciao Chris Hai già il ID di posizione nel vostro listView, implementare la funzione 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();

   }

Se vuoi assing il proprio uso id setTag ()

v.setTag("myownID"+position);

Non è possibile farlo con uno standard ArrayAdapter È necessità di estendere l'ArrayAdapter e sovrascrivere il getItemId () metodo e forse anche il hasStableIds () metodo.

È quindi deve restituire true nel metodo hasStableIds e generare il vostro ID per la voce nella posizione che viene dato al metodo getItemId.

Dopo aver trascorso ore su questo, in questo modo più semplice che ho trovato è stato quello di ignorare Bindview dell'adattatore e impostare un valore di tag contenente _id della riga sulla voce - nel mio caso, si trattava di un pulsante nella 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);
    }
};
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top