0

我是一名学习者,一直在开发一个家庭访问者应用程序,以从访问者的 URL 获取图像。使用我在网上找到的以下代码,我能够通过在屏幕前添加一个意图并在屏幕上添加一个显示“查看访客图像”的按钮来加载图像,但现在我希望我的图像应该在应用程序后立即加载发射。我可以做些什么改变来做到这一点?谢谢你的帮助。

OnClickListener getImageBtnOnClick = new OnClickListener() {
    public void onClick(View view) {
        Context context = view.getContext();
        Editable ed = inputUrl.getText();
        Drawable image = ImageOperations(context,ed.toString(),"image.jpg");
        ImageView imgView = new ImageView(context);
        imgView = (ImageView)findViewById(R.id.image1);
        imgView.setImageDrawable(image);
    }
};

public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.main);
    inputUrl = ((EditText)findViewById(R.id.imageUrl));
    inputUrl.setSingleLine();
    inputUrl.setTextSize(11);
    Button getImageButton = (Button)findViewById(R.id.getImageButton);
    getImageButton.setOnClickListener(getImageBtnOnClick);

}   

private Drawable ImageOperations(Context ctx, String url, String saveFilename) {
    try {
        InputStream is = (InputStream) this.fetch(url);
        Drawable d = Drawable.createFromStream(is, "src");
        return d;
    } catch (MalformedURLException e) {
        e.printStackTrace();
        return null;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

public Object fetch(String address) throws MalformedURLException,IOException {
    URL url = new URL(address);
    Object content = url.getContent();
    return content;
}
4

1 回答 1

2

您可以使用 SmartImageView,它是 Android 标准 ImageView 的替代品,它还允许从 URL 或用户的联系人地址簿加载图像。图像缓存到内存和磁盘以实现超快速加载。

https://github.com/loopj/android-smart-image-view

或者在您的活动的 OnResume 上开始下载图像形式的 url,就像您现在在单独线程中的按钮的单击侦听器中所做的那样,以避免阻塞主 UI 线程。完成下载后,您可以使用工作线程中的处理程序更新图像视图。

您也可以使用异步任务,而不是创建自己的线程和处理程序来更新 UI。有关异步任务的更多信息,请参阅以下链接http://www.vogella.com/articles/AndroidPerformance/article.html

于 2012-11-30T20:31:12.053 回答