-1

私はこのような BaseAdapter を持っています。たとえば、4行しかありません。

この 4 つの convertView の setId を posttion で呼び出します。そして、どこかで notifyDataSetChanged() を呼び出します (上部にボタンを定義し、ボタンをクリックすると notifyDataSetChanged が呼び出されます)、notifyDataSetChanged が呼び出されると、4 つの行が getView() によって呼び出されます。getView() で、id(古い位置) と新しい位置を出力します。行は変わらないので、位置は変わらないと思います。それらは同じになります。しかし、真実はそうではありません。

をプリント:

D/BasePhotoFragment(19230): position:0
D/BasePhotoFragment(19230): old id :3
D/BasePhotoFragment(19230): new id :0
D/BasePhotoFragment(19230): position:1
D/BasePhotoFragment(19230): old id :2
D/BasePhotoFragment(19230): new id :1
D/BasePhotoFragment(19230): position:2
D/BasePhotoFragment(19230): old id :1
D/BasePhotoFragment(19230): new id :2
D/BasePhotoFragment(19230): position:3
D/BasePhotoFragment(19230): old id :0
D/BasePhotoFragment(19230): new id :3

誰か教えてくれませんか?ありがとう、以下はアダプターコードです。

public class PhotosGridAdapter extends BaseAdapter{

private LayoutInflater mInflater;
private Context mContext ;
private List<PhotoEntity> listEntity ;
private int mLinePhotos;
private LinearLayout.LayoutParams mphotoParams = new android.widget.LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 1f);

private final class ViewHolder{
    public List<ImageView> imgs;
}

public PhotosGridAdapter(Context ctx,List<PhotoEntity> entities) {
    this.mContext = ctx ;
    mInflater = LayoutInflater.from(ctx);
    mLinePhotos = Utils.getPhotosNumOfLine(ctx);
    listEntity = entities;
}

@Override
public int getCount() {
    return listEntity != null ? listEntity.size() / mLinePhotos  : 0;
}

@Override
public Object getItem(int position) {
    if( position < listEntity.size() )
    return listEntity.get(position);
    else
    return null;
}

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

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    Log.d(TAG,"position:"+position);
    ViewHolder holder = null;

    if (convertView == null) {
    holder = new ViewHolder();
    convertView = mInflater.inflate(R.layout.row_grid_photos_container, null);
            ....
    convertView.setTag(holder);
    }else{
    holder = (ViewHolder)convertView.getTag();
    }


   int old_id = convertView.getId();

   Log.d(TAG,"old id :"+old_id);
   Log.d(TAG,"new id :"+position);

   if(old_id == position)
       return convertView;

       convertView.setId(position);

       ..... do some bind .
   return convertView;
}

}

4

1 に答える 1

0

notifyDataSetChanged() を呼び出すたびに、ビューが更新され、再作成またはリサイクルされます。つまり、表示されている行ごとに getView メソッドが再度呼び出されます。

モデルが変更された場合にのみ呼び出す必要があります。あなたのケースではlistEntity、新しい要素が追加された場合、またはリスト内の要素のデータが変更された場合にのみ呼び出します。

2 つの異なるレイアウトをインフレートする場合は、メソッド getItemViewType() およびgetViewTypeCount( ) を実装することに注意してください。これにより、getView() メソッドで指定された「convertView」パラメーターが、与えられた位置。あなたの場合、コードは不完全に見えますが、この問題により、リサイクルされている位置に対して間違った convertView パラメーターを受け取っていると思います。これが、ログに異なる ID がある理由です。

于 2013-09-13T11:17:10.533 に答える