我从 SQLite 数据库中提取数据并将其存储在 arrayList 中,以通过 listView 显示联系人信息。然后,用户可以输入 EditText,TextWatcher 会过滤 listView。但是,当这种情况发生时,列表视图项的位置不会在我的 onClickListener 中更新。
我发送给我的 CRUD 活动的 ID 始终是它们被过滤后的位置,而不是它们最初列出时的位置。如何使我的 ListView 项目在过滤后保持其原始位置?或者一种更好的方法来为我的 CRUD 活动提供正确的 ID,而不是通过位置。
public class Search extends AppCompatActivity {
// List view
private ListView lv;
// Listview Adapter
ArrayAdapter<String> adapter;
// Search EditText
EditText inputSearch;
// ArrayList for Listview
ArrayList<String> arrayList = new ArrayList<>();
DBHelper db;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
db = new DBHelper(this);
arrayList = db.getAllContacts();
lv = (ListView) findViewById(R.id.list_view);
inputSearch = (EditText) findViewById(R.id.inputSearch);
adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, arrayList);
lv.setAdapter(adapter);
inputSearch.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
Search.this.adapter.getFilter().filter(cs);
}
@Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
adapter.notifyDataSetChanged();
}
});
lv.setOnItemClickListener(new AdapterView.OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
int id_To_Search = pos + 1;
Bundle dataBundle = new Bundle();
dataBundle.putInt(EXTRA_FLAG, id_To_Search);
// The flag value > 0 is used to signal that the upcoming operation
// is not adding, but updating or deleting
Intent intent = new Intent(getApplicationContext(), CRUDActivity.class);
intent.putExtras(dataBundle); //Intent.putExtras(Bundle extras
startActivity(intent);
}
});
}