如何获取在android中单击的Listview项的值?

Sri*_*idu 9 android listview

我在下面的代码中将ListView项值访问为字符串并在alert中显示它?

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();    
}
Run Code Online (Sandbox Code Playgroud)

zed*_*xff 17

也许这个例子会帮助你

  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();
    }
  });
Run Code Online (Sandbox Code Playgroud)

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


小智 11

这将为您提供所单击项目的准确值.检查日志

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); 
}
Run Code Online (Sandbox Code Playgroud)