2

这是我的列表适配器类

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++;
        }
    }
}
4

1 回答 1

1

getView当您滚动适配器时,Look不能保证位置。每次滚动已使用适配器初始化的列表时,都会初始化新视图。

因此,您要做的就是使用该getView方法。

  • 获取onClickListener您的convertView实例。
  • 不是在 getView 方法中而是在 Adapter 类中初始化一个静态变量。
  • 现在将静态变量分配给适配器方法 的位置getView,显然是在's的onClick方法中。convertViewonClickListener
  • 在同一位置显示您的按钮
于 2013-02-23T06:05:08.390 回答