private String[] data={"Apple","Banana","Orange","Watermelon","Pear","Grape","Pineapple","Strawberry","Cherry","Mango","Apple","Banana","Orange","Watermelon","Pear","Grape","Pineapple","Strawberry","Cherry","Mango"};
//也可以为可以改变大小的数组为ArrayList
List<String> datelist = new ArrayList<String>();
datelist.add("Apple");
datelist.add("Banana");
datelist.add("Orange");
//因为数组下标是从0开始,这里add的index为2即为第三个元素
datelist.add(2, "Watermelon");
datelist.add(1, "Pear");
//datalist.toString()即可获取String类型,但是本身这个ArrayList就可以传给listView,转化为字符是为了展示
listView=findViewById(R.id.listView);
ArrayAdapter adapter = new ArrayAdapter(MainActivity.this,android.R.layout.simple_list_item_1, data);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
@Override
/*
parent:被点击的Adapter对象,是哪个listview;
view: 被点击的Item(可用于获取该item内的组件),是当前listview的item的view的布局,就是可以用这个view,获取里面的控件的id后操作控件
position:被点击的是第几个item(从0开始,0算第一个,类似数组),position是当前item在listview中适配器里的位置
id:当前点击的item在listview里的第几行的位置,通常id与position的值相同
*/
public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
String sth = "总共有:"+parent.getCount()+"行数据"
+ datalist.get(position)
+"\n当前点击第:"+position+"行";
Toast.makeText(MainActivity.this, sth,Toast.LENGTH_SHORT).show();
}
}
);