【问题标题】:OnItemClick to AutoCompleteTextViewOnItemClick 到 AutoCompleteTextView
【发布时间】:2014-02-02 07:19:16
【问题描述】:

我在单击 AutoCompleteTextView 时遇到问题。使用下面的代码,我没有像在 SQLite 数据库中那样获得单击项目的 ID。假设我单击自动完成下拉菜单中显示的第二项。我从 id 2 中的数据库中获取值,而不是数据库中 id 不同的选定项目的值。我确定我的 onItemClick 实现是错误的。我希望有人能帮我弄清楚。很长一段时间以来,我一直对此感到困扰。

我的代码:

  SearchTrainee = (AutoCompleteTextView) findViewById(R.id.search);

    trainees = new ArrayList<HashMap<String, String>>();
    trainees = DatabaseHelper.getInstance().getStoredTrainees();

    String str[] = new String[trainees.size()];
    for (int i = 0; i < trainees.size(); i++) {
        str[i] = trainees.get(i).get("display");
    }

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
            R.layout.search_autocomplete, str);
    SearchTrainee.setAdapter(adapter);
    SearchTrainee.setOnItemClickListener(this);
}

@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {


        System.out.println("Last name: " + trainees.get(arg2).get("last_name"));
         //currentTrainee.setFirstname(trainees.get(arg2).get("first_name"));
        // currentTrainee.setCompany(trainees.get(arg2).get("company"));
        // System.out.println(currentTrainee.getFirstname());


}

【问题讨论】:

  • 不要使用 ArrayAdapter,改用 SimpleCursorAdapter
  • @pskink 有什么具体原因吗??
  • 因为您注意到您丢失了商品 ID

标签: android autocomplete onitemclicklistener


【解决方案1】:

我想你的意思是把最后一行写成这样:

System.out.println("Last name: " + arg0.getItemAtPosition(arg2).get("last_name"));

【讨论】:

  • 并非如此。更不用说缺少演员表,适配器只包含字符串,而不是完整的地图。
  • @user3193470 .get("last_name") 无法实现。对不起
【解决方案2】:

问题在于自动完成视图会过滤显示的内容,使其与您的初始数组不匹配,这意味着您不能依赖 onItemClick 中给出的索引来搜索trainee 数组。

要限制代码中的更改量,您可以执行以下操作:

像这样使用 SimpleAdapter:

SimpleAdapter adapter = new SimpleAdapter(this, trainee, 
        R.layout.search_autocomplete, new String[] {"display"}, 
        new int[] {R.id.text});
 // R.id.text is to be replaced by the id of your TextView in the search_autocomplete layout

然后,在 onItemClick 中,检索代表受训者的 Map,如下所示:

Map<String, String> selectedTrainee = ((Map<String, String>) arg0.getItemAtPosition(arg2));

然后您可以根据需要以任何方式操作该对象(姓氏是selectedTrainee.get("last_name")

【讨论】:

  • 你是个了不起的家伙。它就像魅力一样。在这种情况下,我也遇到了其他问题。由于您的解决方案,我也设法解决了这个问题。非常感谢。祝你有美好的一天!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-10
  • 1970-01-01
  • 1970-01-01
  • 2021-09-19
相关资源
最近更新 更多