如何从ListView获取字符串?

时间:2012-12-21 10:52:36

标签: android android-listview

如何在onItemLongClick中获取所选的项目数据?

  listView.setOnItemLongClickListener(new OnItemLongClickListener() {

                @Override
                public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                        int arg2, long arg3) {
                    //              
                    return false;
                }
            });

3 个答案:

答案 0 :(得分:9)

final ListView lv = (ListView) findViewById(R.id.ListView01);

lv.setOnItemClickListener(new OnItemClickListener() {
  public void onItemClick(AdapterView<?> myAdapter, View myView, int pos, long mylng) {
    String selectedFromList =(lv.getItemAtPosition(pos).toString());
    // this is your selected item
  }                 
});

答案 1 :(得分:2)

 listView.setOnItemLongClickListener(new OnItemLongClickListener() 
 {
    @Override
    public boolean onItemLongClick(AdapterView<?> arg0, View arg1,int arg2, long arg3) 
    {
         String item = ArryList.get(arg2); 
         Toast.makeText(getBaseContext(), item,
         Toast.LENGTH_LONG).show();          
         return false;
     }
 });

答案 2 :(得分:0)

如果从xml,json,database等解析数据集,最好创建自定义模型,即 你的模特:

public class YourModel
{
    private int id = -1;
    private String title = "";

    public int getId()
    {
        return id;
    }

    public void setId(int id)
    {
        this.id = id;
    }

    public String getTitle()
    {
        return title;
    }

    public void setTitle(String title)
    {
        this.title = title;
    }
}

活动:

private YourModel yourModel;

@Override
public void onCreate(Bundle savedInstanceState)
{
    lstView.setOnItemClickListener(new OnItemClickListener()
    {
        @Override
        public void onItemClick(AdapterView<?> parent, View v, int position,
                    long id)
        {
            detailsModel = ((YourAdapter) lstView.getAdapter()).getItem(position);
            Toast.makeText(getApplicationContext, yourModel.getTitle(),
                Toast.LENGTH_LONG).show();
        }
    }
}