这是我的列表适配器类
public class ListDemoAdapter extends BaseAdapter{
private String[] name={"aa","bb","cc","dd","ee","ff","gg","hh","ii","jj","kk"};
private Context context;
private LayoutInflater inflater;
public ListDemoAdapter(Context ctx) {
context=ctx;
inflater=(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return name.length;
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return name[position];
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View view=convertView;
ViewHolder holder;
if(view==null)
{
holder=new ViewHolder();
view=inflater.inflate( R.layout.listitem, null);
holder.tv=(TextView)view.findViewById(R.id.tv);
holder.btn=(Button)view.findViewById(R.id.addbtn);
holder.rl=(LinearLayout)view.findViewById(R.id.runtimerl);
view.setTag(holder);
}else{
holder=(ViewHolder) view.getTag();
}
holder.tv.setText(name[position]);
holder.btn.setOnClickListener((OnClickListener) context);
return view;
}
private class ViewHolder{
private TextView tv;
private Button btn;
private LinearLayout rl;
}
}
当我们单击按钮时,将生成运行时按钮,但是当我们滚动列表视图时,运行时创建的按钮在另一行代码中发生更改,如下所示:
public class AndroidListDemoActivity extends Activity implements OnClickListener{
private ListView list;
public static int pos=0;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
list=(ListView)findViewById(R.id.list);
list.setAdapter(new ListDemoAdapter(this));
}
@Override
public void onClick(View v) {
if(v.getId()==R.id.addbtn){
View view=(View) v.getParent();
LinearLayout rl=(LinearLayout)view.findViewById(R.id.runtimerl);
Button btn=new Button(this);
btn.setText(""+pos);
btn.setTag(btn+"pos");
rl.addView(btn);
pos++;
}
}
}