您好我正在使用android.I使用数组列表创建了一个列表视图。现在,我如何向每个列表项添加Action以及如何获取该项的列表位置。请帮帮我,谢谢
这是我的代码
public class MainActivity extends Activity {
private ListView lv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView lv=(ListView)findViewById(R.id.listView1);
ArrayList<String> list=new ArrayList<String>();
list.add("aaaa");
list.add("bbbb");
list.add("cccc");
list.add("dddd");
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
this,
android.R.layout.simple_list_item_1,
list);
lv.setAdapter(arrayAdapter);
}
}
答案 0 :(得分:6)
您需要实施ListView setOnItemClickListener
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// ListView Clicked item index
int itemPosition = position;
// ListView Clicked item value
String itemValue = (String) listView.getItemAtPosition(position);
// Show Alert
Toast.makeText(getApplicationContext(),
"Position :"+itemPosition+" ListItem : " +itemValue , Toast.LENGTH_LONG)
.show();
}
});
有关详情,请转至Documentation。
答案 1 :(得分:0)
您还可以使用以下代码在setOnItemClickListener中获取ListView的所选项目:
listView1.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
int itemPosition = position;
String itemname = ((TextView)view).getText().toString();
Toast.makeText(getBaseContext(), "Item: " + itemname + " is at position: " + itemPosition, Toast.LENGTH_LONG).show();
}
});
答案 2 :(得分:0)
由于listview单元格的位置和arraylist的索引相同。所以我们可以通过listview的单元格位置轻松地从arraylist中获取项目。
listView1.setOnItemClickListener(new OnItemClickListener()
{
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,long id)
{
int position=position;
String item=marraylist.get(position).toString();
}
}