ListView可以说是Android原生开发最基本、最重要的控件之一,良好的使用ListView可以让自己的项目得到提高,下面是ListView最简单的应用方式
定义ListView
list_view = (ListView) findViewById(R.id.list_view);
下面是测试的数据
plans = new ArrayList<String>();
for (int i = 0; i < 100; i++) {
plans.add("测试" );
} 设置自己的适配器,设置每一条的点击事件
MyAdapter mAdapter = new MyAdapter(this, plans);
list_view.setAdapter(mAdapter);
list_view.setOnItemClickListener(new OnItemClickHandler());
初始化适配器,填充数据
public MyAdapter(Context context, List<String> datas) {
mContext = context;
mInflater = LayoutInflater.from(mContext);
mDatas = datas;
// this.onClickListener = onClickListener;
} 得到ListView个数
@Override
public int getCount() {
return (mDatas != null ? mDatas.size() : 0);
}
得到ListView的item
@Override
public Object getItem(int position) {
return (mDatas != null ? mDatas.get(position) : null);
}
得到ListView的item的ID
@Override
public long getItemId(int position) {
return position;
}
ListViewitem的item填充,button点击事件的书写
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
// 下拉项布局
convertView = mInflater.inflate(R.layout.list_item_btn, null);
holder = new ViewHolder();
holder.avatar = (ImageView) convertView.findViewById(R.id.avatar);
holder.title = (TextView) convertView.findViewById(R.id.title);
holder.btn = (Button) convertView.findViewById(R.id.btn);
convertView.setTag(holder); } else {
holder = (ViewHolder) convertView.getTag();
} String plan = mDatas.get(position); if (plan != null) { holder.title.setText(plan);
holder.btn.setText(mDatas.get(position)); // 通常将position设置为tag,方便之后判断点击的button是哪一个
//按钮的点击事件
holder.btn.setTag(position);
holder.btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) { Button btn = (Button) v;
int pos = (Integer) btn.getTag();
System.out.println(" position2 :" + pos);
System.out.println(" data2 :" + mDatas.get(pos).toString());
btn.setText("111");
mDatas.set(position,"111"); }
});
}
return convertView;
} 效果图:
demo github地址:https://github.com/tempest1/ListBtn