【问题标题】:Application crashes trying to retrieve view contents from ListView using SimpleAdapter尝试使用 SimpleAdapter 从 ListView 检索视图内容的应用程序崩溃
【发布时间】:2012-06-15 06:05:21
【问题描述】:

我在尝试检索用户在 ListView 中单击的视图内容时遇到问题。我的 ListView 是使用 SimpleAdapter 设置的,由列表中每个项目的“标题”和“子标题”组成。这些是使用 HashMap 存储的。

在活动中也是一个微调器,当用户在微调器中选择一个项目时,ListView 会更新。这工作正常,我只是认为有必要提及活动中发生的事情。

我要做的是检索用户选择的项目,以便我可以根据他们的选择引导他们进行新活动(现在只是尝试使用 Toast 显示视图内容)。我想检索项目的“engExp”键下存储的内容。

这是我的代码:

    // HASHMAP FOR LISTVIEW
    List<HashMap<String, String>> fillMaps = new ArrayList<HashMap<String, String>>();
    for(int x = 0; x < expressionListForModule.getCount(); x++) {
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("engExp", expressionListForModule.getString(0));
        map.put("japDef", expressionListForModule.getString(1));
        fillMaps.add(map);
        expressionListForModule.moveToNext();
    }

    // SETUP LISTVIEW
    SimpleAdapter adapter2 = new SimpleAdapter(this, fillMaps, android.R.layout.simple_list_item_2, new String[] {"engExp","japDef"}, new int[] {android.R.id.text1, android.R.id.text2});
    ListView lv = (ListView) findViewById(R.id.expressionList);
    lv.setAdapter(adapter2);
    lv.setTextFilterEnabled(true);
    lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Toast.makeText(getApplicationContext(), ((TextView) view).getText(), Toast.LENGTH_LONG).show();
        }
    });

具体来说,导致应用程序崩溃的项目是: ((TextView) 视图).getText()

如果您需要查看我的更多代码,请告诉我。

任何帮助表示赞赏,在此先感谢。

【问题讨论】:

  • 您必须编写代码以从 TextView 获取文本,该文本位于 onItemclick()) 方法中,并且通过使用视图参数,您可以获得该文本...试试这个 String contentForLink=view。 getText().toString();
  • 这会引发如下错误:方法 getText() 未定义 View 类型

标签: android listview crash simpleadapter


【解决方案1】:

试试

lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        TextView v = (TextView) view.findViewById(android.R.id.text1);
        String contentForLink = v.getText().toString();
        Toast.makeText(getApplicationContext(), contentForLink, Toast.LENGTH_LONG).show();
    }
});

【讨论】:

  • 这肯定会阻止崩溃!然而,现在正在发生一些奇怪的事情。显示的是 Spinner 项本身的文本,而不是显示列表项本身的内容。谢谢。
  • 我不确定为什么它不能使用您第一次输入的代码。但再次输入后,它完美地工作了!一定是我在某个地方犯了一个愚蠢的错误。非常感谢。
猜你喜欢
  • 1970-01-01
  • 2016-03-12
  • 1970-01-01
  • 2022-01-01
  • 2018-12-22
  • 1970-01-01
  • 2016-02-11
  • 2014-01-29
  • 1970-01-01
相关资源
最近更新 更多