Android慢GridView

时间:2014-10-07 20:17:06

标签: android performance gridview android-fragments

我是Android开发新手,遇到了性能问题。当我的GridView有太多的项目时,它变得有点慢。有没有办法让它表现得更快一点?

以下是使用的代码:

适配器:

public class CharactersAdapter extends BaseAdapter {
private Context mContext;
private int screenSize;
private int columns;
// Constructor

public CharactersAdapter(Context c,int screenSize) {
    this.screenSize=screenSize;
    mContext = c;
}

public CharactersAdapter(Context c) {
    mContext = c;
}

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

@Override
public Object getItem(int i) {

    return charPics[i];
}

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

@Override
public View getView(int i, View convertView, ViewGroup viewGroup) {
    ImageView imageView;
    this.columns=mContext.getResources().getInteger(R.integer.grid_columns);
    if (convertView == null) {

        imageView = new ImageView(mContext);
        imageView.setLayoutParams(new GridView.LayoutParams(screenSize /this.columns,screenSize      /this.columns));
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
    }else{
        imageView = (ImageView) convertView;
    }
    imageView.setImageDrawable(mContext.getResources().getDrawable(charPics[i]));
    return imageView;
}}

片段

public class CharacterFragment extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    DisplayMetrics displaymetrics = new DisplayMetrics();
    getActivity().getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
    int screenWidth = displaymetrics.widthPixels;


    View rootView = inflater.inflate(R.layout.fragment_character, container, false);
    GridView gridview = (GridView)rootView.findViewById(R.id.gridview);
    gridview.setAdapter(new CharactersAdapter(getActivity(),screenWidth));

    gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View v,
                                int position, long id) {

            Intent i = new Intent(getActivity().getApplicationContext(), CharacterActivity.class);
            // Pass image index
            i.putExtra("pos", position);
            startActivity(i);
        }
    });

    return rootView;
}

我做错了什么?....

2 个答案:

答案 0 :(得分:3)

我真的建议你在那里使用Holder Pattern,在其中你保存你创建的视图以便重用并保存内存以提供更多性能,here是一个非常好的教程。此外,对于图像加载,您可以使用通用图像加载器,它将使图像异步加载UIL,因此您的UI线程不会变慢。祝你好运

答案 1 :(得分:0)

我最终使用Picasso库来加载图像。它就像一个魅力。