Atribuindo ID a uma linha em um Android ListView
-
27-09-2019 - |
Pergunta
Eu tenho uma ListView. Quando um item no ListView é tocado, ele carrega uma subview. Quero atribuir um ID a cada linha do ListView, para que eu possa passar esse ID para o Subview. Como atribuo um ID específico a cada linha no ListView?
Aqui está como estou carregando o ListView:
setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, mArrayList));
Solução
Veja como resolvi o problema. Eu obtive os funcionários_ids e funcionários do banco de dados local do SQLite, então criei uma lista de Arrayeeenamesarray e uma lista de funcionários do Funcionário ao mesmo tempo. Assim, o funcionárioidArray [0] corresponderia ao Employeenamearray [0], Funcionário [1] corresponderia com o Employeenamearray [1], etc.
Depois que os Arraylists foram criados, alterei o EmployeenAmearray no ListView.
Mais tarde, no OnListItemClick, retiro a posição da linha ListView selecionada. Essa 'posição' será corrosto para a posição nos Arraylists - assim, se eu selecionar a primeira linha no ListView, a posição será zero e o Employeeenamearray [0] corresponde ao Funcionário [0]. Pego a entrada de coroloação do Funcionário e o pressiono para a próxima atividade usando o 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
}
}
Outras dicas
Olá Chris, você já tem o ID da posição em sua ListView, implemente a função 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 você quiser assar sua própria identificação, use Settag ()
v.setTag("myownID"+position);
Você não pode fazer isso com um padrão Arrayadapter Você precisa estender o Arrayadapter e substituir o getItemid () método e talvez também o hasstableIds () método.
Você deve retornar verdadeiro no método HasStableIds e gerar seu ID para o item na posição que é fornecida ao seu método getItemid.
Depois de gastar horas nisso, essa maneira mais fácil que achei foi substituir o BindView do adaptador e definir um valor de tag que contém o _id da linha no item - no meu caso, era um botão na linha 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);
}
};