android - 在 Android 上,在 GridView 中显示来自文件的图像非常慢

标签 android gridview

我有两个问题:

  1. 在gridview中显示图片之前的延迟很长:15s!!!而且我不知道如何解决这个问题。

  2. 当图像加载到 gridview 中并且我尝试向下(或向上)滚动以查看其余图像时,手机需要很长时间才能显示它们。此外,如果我滚动得非常快,应用程序就会停止。

备注:e 变量用于在每次跳跃 +1 时为背景赋予不同的颜色(绿色/蓝色/绿色....)

提前致谢,代码如下:

代码:res/layout/main_activity.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >



     <GridView
    android:id="@+id/PhoneImageGrid"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:columnWidth="90dp"
    android:gravity="center"
    android:horizontalSpacing="10dp"
    android:numColumns="auto_fit"
    android:stretchMode="columnWidth"
    android:verticalSpacing="5dp" />



</RelativeLayout>

代码:MainActivity.java

public class MainActivity extends Activity {

    private int count;
    private Bitmap[] thumbnails;
    private boolean[] thumbnailsselection;
    private String[] arrPath;
    private ImageAdapter imageAdapter;
    ArrayList<String> f = new ArrayList<String>();// list of file paths
     int e=0; // To change the background color 
    String[] Files;
    ImageView selection;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // get images paths and store them in f
            getFromSdcard();

           GridView imagegrid = (GridView) findViewById(R.id.PhoneImageGrid);

            imagegrid.setAdapter(new ImageAdapter(this));

    }

    /*GET images paths */
    public void getFromSdcard()
    {

        File file=  new File("mnt/sdcard/DCIM/100ANDRO");

            if (file.exists())
            {
                Files = file.list();

                for (int i = 0; i < Files.length; i++)
                {
                    f.add(file.getAbsolutePath() + File.separator + Files[i]);
              }

            }

    }


    public class ImageAdapter extends BaseAdapter {

        Context ctxt;

        public ImageAdapter(Context c) {

                this.ctxt=c;
                }

        public int getCount() {
            return f.size();
        }

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

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


        public void setColorType(){
            if(e==0)
                e= 1;
            else{e= 0;}

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


            ImageView c;

            if (convertView == null) {
                c= new ImageView(ctxt);

                //Bitmap myBitmap = BitmapFactory.decodeFile(f.get(position));// Files[position]
                c.setLayoutParams(new GridView.LayoutParams(80,80));
                c.setScaleType(ScaleType.CENTER_CROP);
                c.setPadding(8,8,8,8);

                if(e==0){
                     c.setBackgroundColor( -65536);
                     setColorType();
                    }
                else{
                    setColorType();
                    c.setBackgroundColor( -16711936);
                }

            }
            else {
                c= (ImageView) convertView;

                if(e==0){
                     c.setBackgroundColor( 00000);
                     setColorType();
                    }

            }

            Bitmap myBitmap = decodeFile(new File(f.get(position)));
            c.setImageBitmap(myBitmap);

            return c;
        }


    }



// To solve the issue of uploading image and avoid error ** Out of memory   

    private Bitmap decodeFile(File f){
        try {
            //Decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(new FileInputStream(f),null,o);

            //The new size we want to scale to
            final int REQUIRED_SIZE=70;

            //Find the correct scale value. It should be the power of 2.
            int scale=1;
            while(o.outWidth/scale/2>=REQUIRED_SIZE && o.outHeight/scale/2>=REQUIRED_SIZE)
                scale*=2;

            //Decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize=scale;


            return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
        } catch (FileNotFoundException e) {}
        return null;
    }


}

最佳答案

替换这些行

Bitmap myBitmap = decodeFile(new File(f.get(position)));
c.setImageBitmap(myBitmap);

if(c.getTag() != null) {
    ((ImageGetter) c.getTag()).cancel(true);
}
ImageGetter task = new ImageGetter(c) ;
task.execute(new File(f.get(position)));
c.setTag(task);

并创建在后台获取图像的类ImageGetter:

public class ImageGetter extends AsyncTask<File, Void, Bitmap> {
    private ImageView iv;
    public ImageGetter(ImageView v) {
        iv = v;
    }
    @Override
    protected Bitmap doInBackground(File... params) {
        return decodeFile(params[0]);
    }
    @Override
    protected void onPostExecute(Bitmap result) {
        super.onPostExecute(result);
        iv.setImageBitmap(result);
    }
}

关于android - 在 Android 上,在 GridView 中显示来自文件的图像非常慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19293337/

相关文章:

android - DialogFlow Android SDK需要grpc-okhttp,但添加它会导致Socket IO CLient崩溃

java - 从 Android 访问数据库的最佳方式

android - 使用 OpenCV 进行叶病检测和识别

android - Gridview 使用异步任务填充问题

ASP.Net GridView GridViewDeleteEventArgs.Keys 空

android - java.lang.RuntimeException : Cannot start "jarsigner" process, 请将其添加到 PATH

android - 是否可以将 Android View 渲染到 OpenGL FBO 或纹理?

c# - 'GridView' 必须放在带有 runat=server 的表单标签内。

c# - 通过 asp.net 中的保存按钮将数据绑定(bind)到 gridview 后,保存按钮单击事件会在刷新页面时触发

asp.net - ASP 存储过程到 GridView