列表视图项在android中重复?

时间:2011-03-31 13:07:18

标签: android android-widget

我使用下面的代码列出数组中的几个项目,而滚动列表视图项目附加更多数据退出数组我不知道我犯了什么错误。

任何人都指出我犯了错误。

private static String array_spinner_subcategories[];
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE); 
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        setContentView(R.layout.sub_categories);

        setSubCat();

        ListView sub_categories=(ListView)findViewById(R.id.sub_catlist);
        sub_categories.setAdapter(new EfficientAdapter(this));

        sub_categories.setAdapter(adapter);
        sub_categories.setOnItemClickListener(subcatlistener);

        cr=getContentResolver();
    }
    public String[] setSubCat(){
        recordDB=new Viddatabase(this);
        db=recordDB.getWritableDatabase();
        array_spinner_subcategories=recordDB.subcategoriesList(db);
        recordDB.close();
        return array_spinner_subcategories;
}
    private OnItemClickListener subcatlistener = new OnItemClickListener() {
        public void onItemClick(AdapterView parent, View v, int position,
   long id) {
              System.gc();
              Toast.makeText(SubCategories.this,array_spinner_subcategories[position],
                        Toast.LENGTH_LONG).show();

        }
   };

   private static class EfficientAdapter extends BaseAdapter {
       private LayoutInflater mInflater;

       public EfficientAdapter(Context context) {
       mInflater = LayoutInflater.from(context);

       }

       public int getCount() {
       return array_spinner_subcategories.length;
       }

       public Object getItem(int position) {
       return position;
       }

       public long getItemId(int position) {
       return position;
       }

       public View getView(int position, View convertView, ViewGroup parent) {
         System.gc();
       ViewHolder holder;

       if (convertView == null) {
       convertView = mInflater.inflate(R.layout.albumlist, null);
       holder = new ViewHolder();

       holder.subCategories = (TextView) convertView.findViewById(R.id.albumDetails);
       holder.subCategories.setText(array_spinner_subcategories[position]);


       convertView.setTag(holder);
       } else {
       holder = (ViewHolder) convertView.getTag();
       }


       return convertView;
       }

       static class ViewHolder {

       TextView subCategories;



       }

       }

2 个答案:

答案 0 :(得分:2)

holder.subCategories.setText(array_spinner_subcategories[position]);方法中的getView()行移到else块下面

答案 1 :(得分:1)

在getView方法中,您只在创建新视图时在视图中设置数据。

ListView回收视图,因此您很可能会在视图中传递以重用,这就是它被称为转换视图的原因。

每次调用此视图时,您都需要在视图上调用setText,否则您只是将convertview设置为不变,因此重复使用相同的值。