【问题标题】:How to get the value of a Listview item which is clicked in android?如何获取在 android 中单击的 Listview 项的值?
【发布时间】:2010-06-07 09:34:28
【问题描述】:

我有以下代码将 ListView 项值访问为字符串并在警报中显示?

ListView shot = getListView();
shot.setOnItemClickListener(this);

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

    String S = arg1.getContext().toString();
    AlertDialog.Builder alertbox = new AlertDialog.Builder(this);

    // set the message to display
    alertbox.setMessage(S).show();    
}

【问题讨论】:

  • 请在提问时多花点功夫。我不能完全理解你的问题。你想做什么?什么有效,什么无效?
  • 提示:不要使用arg0arg1等作为参数名称。它使源代码完全不可读。其中之一实际上是您正在寻找的信息,所以如果您使用了专有名称,您就不需要问这个问题。

标签: android listview


【解决方案1】:

这会为您提供所点击项目的确切值。查看日志

ListView shot = getListView();
shot.setOnItemClickListener(this);

public void onItemClick(AdapterView<?> parent, View view, int position,long id) {

    String val =(String) parent.getItemAtPosition(position);
    System.out.println("Value is "+val); 
}

【讨论】:

  • 为我触发了 ClassCastException!!
【解决方案2】:

也许这个例子会对你有所帮助

  lv.setOnItemClickListener(new OnItemClickListener() {
    public void onItemClick(AdapterView<?> parent, View view,
        int position, long id) {
      // When clicked, show a toast with the TextView text
      Toast.makeText(getApplicationContext(), ((TextView) view).getText(),
          Toast.LENGTH_SHORT).show();
    }
  });

https://developer.android.com/reference/android/widget/ListView.html

【讨论】:

    【解决方案3】:

    获取模型的价值

    adaptor.getItem(position).getCardName();

    【讨论】:

      【解决方案4】:

      也许你可以试试这个

      String data = (String)shot.getItemAtPosition(arg2);
      AlertDialog.Builder adb = new AlertDialog.Builder(arg1.getContext());              
      adb.setMessage(data).show();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-03-21
        • 1970-01-01
        • 1970-01-01
        • 2012-09-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多