getting item's name when clicking a ListView

2019-05-21 07:24发布

问题:

Is there any way I can capture a name of an item clicked in a list view when using "onItemLongClickListiner" ? I know I can capture position etc but I need a name

回答1:

I suppose that you ListView is filled up with String object:

public boolean onItemLongClick (AdapterView<?> parent, View view, int position, long id) {
 String name = (String) parent.getItemAtPosition(position);
}

AdapterView.getItemAtPosition(position) gets the data associated with the specified position in the list.



回答2:

You can use lv.getItemAtPosition(position) to get the text based on the index position

lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View v, int position,
        long arg3) 
{
    String name = arg0.getItemAtPosition(position).toString()
}
});

For more info

getItemAtPosition



回答3:

Try this..

list.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            //inflated row layout textview
            TextView tagText = (TextView) view.findViewById(R.id.txt_text);
            String tag = tagText.getText().toString();
            Toast.makeText(getApplicationContext(),
            "Element Name " + tag + " Clicked", Toast.LENGTH_SHORT).show();
        }
    });


回答4:

It has worked for me.

listtview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
  @Override
  public void onItemClick(AdapterView<?> adapterView, View view, int position, long l){
       String selected = (String) adapterView.getItemAtPosition(i);
       Toast.makeText(getApplicationContext(),"This is"+selected,Toast.LENGTH_LONG).show();
  }
});