android listview displays false data after scrolling (custom adapter)

后端 未结 3 2124
感动是毒
感动是毒 2021-01-04 22:06

I\'ve got a strange problem that drives me crazy. In my android application I customized my own adapter that extends from ArrayAdapter. The items of the ListView to which I

3条回答
  •  既然无缘
    2021-01-04 22:36

    I had a similar problem with multiple item types in the list. In my case the list item was either a section (label) item or a common list item.

    To work with such types of lists, you should override getViewTypeCount and getItemViewType methods. Something like this:

    private static final int ITEM_VIEW_TYPE_ITEM = 0;
    private static final int ITEM_VIEW_TYPE_SEPARATOR = 1;
    
    @Override
    public int getViewTypeCount() {
        return 2;
    }
    
    @Override
    public int getItemViewType(int position) {
        return this.getItem(position).isSection() ? ITEM_VIEW_TYPE_SEPARATOR : ITEM_VIEW_TYPE_ITEM;
    }
    
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        final Item item = this.getItem(position);
    
        if (convertView == null) {
            convertView = mInflater.inflate(item.isSection() ? R.view1 : R.view2, null);
        }
    
        if(item.isSection()){
            //...
        }
        else{
            //...
        }
    
        return convertView;
    }
    

    Then the convertView parameter will always be correct and contain that type which you need.

    And another thing: you explicitly added the public Param[] params field when you already have it in the base class ArrayAdapter.

    I would recommend to inherit from the BaseAdapter class.

    Edit: Here is the code which you can try to use in order to make your Spinner work:

    sp.setTag(p);
    sp.setOnItemSelectedListener(new OnItemSelectedListener(){
    public void onItemSelected(AdapterView parent, View convertView, int pos, long id) {
        Param currentItem = (Param)parent.getTag();
        currentItem.setDefData(currentItem.getData().get(pos));
        currentItem.setChanged(true);
    }
    //...
    

    Try to use the combination of the getTag and setTag methods. I remember that I had similar problems with event handlers and final variables, but I completely forgot the cause of them, so I can't explain exactly why this happens.

提交回复
热议问题