GridView交换项目

时间:2018-11-05 00:53:32

标签: android gridview scroll baseadapter android-gridview

你好,我的朋友们我有问题。当我在GridView中向下滚动并向上滚动时,项目的顺序会发生变化。我希望所有主题保留在同一位置。在下面可以找到我的代码。如果有人可以帮助我,那就太好了,因为这是一个非常令人讨厌的错误。

public class GridAdapter extends BaseAdapter {

    Context context;
    private final String [] data;
    View view;
    LayoutInflater layoutInflater;
    int[] i = {
        R.drawable.blue,
        R.drawable.green,
        R.drawable.yellow,
    };

    public GridAdapter(Context context, String[] data) {
        this.context = context;
        this.data = data;
    }

    @Override
    public int getCount() {
        return data.length;
    }

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

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        if(convertView==null){
            layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = new View(context);
            view = layoutInflater.inflate(R.layout.single_item,null);

            ImageView imageView = (ImageView) view.findViewById(R.id.imageView);
            TextView textView = (TextView) view.findViewById(R.id.textView);
            Random rand = new Random();
            int  n = rand.nextInt(i.length);
            imageView.setImageResource(i[n]);
            textView.setText(data[position]);
        }else{
           view = (View)convertView;
        }

        return view;
    } }

2 个答案:

答案 0 :(得分:0)

to faster the performance use ViewHolder like below
@Override
public View getView(int position, View convertView, ViewGroup parent) {
    if(convertView == null) {
        final LayoutInflater layoutInflater = LayoutInflater.from(mContext);
        convertView = layoutInflater.inflate(R.layout.single_item, null);  
        final ImageView imageView = (ImageView)convertView.findViewById(R.id.imageView);
        final TextView textView = (TextView)convertView.findViewById(R.id.textView);
        final ViewHolder viewHolder = new ViewHolder(imageView, textView);
        convertView.setTag(viewHolder);
    }
    Random rand = new Random();
    int  n = rand.nextInt(i.length);
    final ViewHolder viewHolder = (ViewHolder)convertView.getTag();
    viewHolder.imageView.setImageResource(i[n]);
    viewHolder.textView.setText(data[position]);
    return convertView;
} 
 private class ViewHolder {
    private final TextView imageView;
    private final TextView textView;
    public ViewHolder(TextView imageView, TextView textView) {
      this.imageView = imageView;
      this.textView = textView;
    }
  }

答案 1 :(得分:0)

在添加这两行后对我有用:

@Override

public int getViewTypeCount() {

    return getCount();
}

@Override
public int getItemViewType(int position) {

    return position;
}