用户选择时,从URL查看图像并在ImageView中放置

时间:2012-06-06 07:33:25

标签: android image url imageview

开发Frame应用程序。为此,我想从网址显示图像(帧)。网址有超过50张图片。为此,我使用gridview但它缺少一些点,如

1.加载图像的速度非常慢。

2.我们在代码时声明图像的名称和大小,以便我们在发布应用程序后不会将图像添加到网址。

我需要解决这些问题。请有人给我建议。

2 个答案:

答案 0 :(得分:1)

使用延迟加载列表视图的以下链接,这将对您有所帮助。

Lazy Loading ListView

使用上面的链接代码和添加另一个活动和另一个显示所选图像的布局,如果你有任何问题,请告诉我,我会在这里填写完整的代码。

答案 1 :(得分:0)

1.加载图片的速度非常慢。

  

这将取决于您的带宽和设备缓存。

<强> 2。我们在代码时声明图像的名称和大小,以便我们在发布应用程序后不会将图像添加到网址。

您可以拥有预定义的URL,因此在代码时您可以将图像名称附加到url.and准备好URL后,使用AsyncTask逐个下载图像\

以下代码段会对您有所帮助。

<强> DownloadHelper.java

public interface DownloadHelper
{
    public void OnSucess(Bitmap bitmap);
    public void OnFailure(String response);
}

<强> MainActivity.java

public class GalleryExample extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.main);

        DownloadHelper downloadHelper = new DownloadHelper()
        {
            @Override
            public void OnSucess(Bitmap bitmap)
            {
                ImageView imageView=(ImageView)findViewById(R.id.imageView);
                imageView.setImageBitmap(bitmap);
            }

            @Override
            public void OnFailure(String response)
            {
                Toast.makeText(context, response, Toast.LENGTH_LONG).show();
            }
        };
        new MyTask(this,downloadHelper).execute("image url");
    }

<强> MyTask.java

public class DownloadTask extends AsyncTask<String, Integer, Object>
{
    private Context context;
    private DownloadHelper downloadHelper;
    private ProgressDialog dialog;


    public DownloadTask(Context context,DownloadHelper downloadHelper)
    {
        this.context = context;

    }

    @Override
    protected void onPreExecute()
    {
        dialog = new ProgressDialog(context);
        dialog.setTitle("Please Wait");
        dialog.setMessage("Fetching Data!!");
        dialog.setCancelable(false);
        dialog.show();
        super.onPreExecute();
    }

    @Override
    protected Object doInBackground(String... params)
    {
        URL aURL = new URL(myRemoteImages[position]);
        URLConnection conn = aURL.openConnection();
        conn.connect();
        InputStream is = conn.getInputStream();

        BufferedInputStream bis = new BufferedInputStream(is);
        /* Decode url-data to a bitmap. */
        Bitmap bm = BitmapFactory.decodeStream(bis);
        bis.close();
        is.close();
        return bm;
    }

    @Override
    protected void onPostExecute(Object result)
    {
        dialog.dismiss();
        if (result != null)
        {
            downloadHelper.OnSucess((Bitmap)result);
        } 
        else
        {
            downloadHelper.OnFailure("Error in Downloading Data!!");
        }
        super.onPostExecute(result);
    }
}