2013-02-23 66 views
1

運行時添加的按鈕改變位置這是我listadapter類當我們滾動列表視圖,在android系統

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

請讓問題中的代碼是可讀的 – Riskhan 2013-02-23 05:49:48

回答

0

getView不保證該位置,當您通過適配器滾動。每次滾動已使用適配器初始化的列表時,都會初始化新的視圖。

所以,你需要做的是玩getView方法。

  • convertView實例上獲取onClickListener
  • 初始化不在getView方法中但在Adapter類中的靜態變量。
  • 現在很明顯,分配convertViewonClickListeneronClick方法內部適配器的getView方法的靜態變量位置
  • 在相同的地方可見您的按鈕
相關問題