本文主要是介绍简单的android Listview使用例子,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
为了熟悉Listview的使用,做了一个小例子联系一下,
主要步骤:
1. 在MainActivity中,创建一个adapter对象(可以是android自带的ArrayAdapter,也可以是自定义的如SongAdapter)
2. 如果自定义,就要创建ListView的子项,如song_listview_item.xml
3. 创建ListView对象,并用setAdapter方法把adapter装进去
4. 用setOnItemClickListener设置点击事件
需要注意的是,在自定义的SongAdapter中最好能用convertView参数和一个缓存控件实例的类对象如ViewHolder来优化ListView的运行效率。
具体见源码
/*SongAdapter*/
public class SongAdapter extends ArrayAdapter<SongInfo> {private int resourceId;public SongAdapter(Context context, int resourceId, List<SongInfo> objects) {super(context, resourceId, objects);this.resourceId = resourceId;}@Overridepublic View getView(int position, View convertView, ViewGroup parent) {View view;ViewHolder holder;SongInfo songInfo = getItem(position);if (null == convertView) {view = LayoutInflater.from(getContext()).inflate(resourceId, null);holder = new ViewHolder();holder.tvSongName = (TextView)view.findViewById(R.id.tvSongName);holder.tvSinger = (TextView)view.findViewById(R.id.tvSinger);view.setTag(holder);}else {view=convertView;holder = (ViewHolder)view.getTag();}
// TextView tvSongName = (TextView)view.findViewById(R.id.tvSongName);
// TextView tvSinger = (TextView)view.findViewById(R.id.tvSinger);holder.tvSongName.setText(songInfo.getSongName());holder.tvSinger.setText(songInfo.getSinger());return view;}//缓存子布局中的控件实例class ViewHolder{TextView tvSongName;TextView tvSinger;}
}
SongInfo.java
public class SongInfo {private String songName;private String singer;public SongInfo(String songName, String singer) {this.songName = songName;this.singer = singer;}public String getSongName() {return songName;}public
这篇关于简单的android Listview使用例子的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!