Reputation: 23
This is my listadapter class
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;
}
}
and when we click on button then runtime button will generate but when we scroll list view then runtime created button changed in another row code is given below :
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++;
}
}
}
Upvotes: 2
Views: 481
Reputation: 4013
Look getView
doesn't guarantee the position , when you scroll through the Adapter. As new Views are initialized every time you scroll through the list that has been initialized with adapter.
So, What you have to do is play with the getView
method.
onClickListener
on your convertView
instance.getView
method obviously inside the onClick
method of the convertView
's onClickListener
.Upvotes: 1