简体   繁体   English

如何将图像从文件加载到Android中的内存中?

[英]How to load image from file into the memory in android?

I have application with multitab. 我有多表应用程序。 and user have choice to select background image from file. 用户可以选择从文件中选择背景图像。 But when user change the tab the performance is not good and application is going slow down. 但是,当用户更改选项卡时,性能不好,应用程序运行缓慢。 So I am looking for the way that first load image into the ram and then load into the background. 因此,我正在寻找先将图像加载到ram然后再加载到背景的方式。 But I don't have any idea how can I do that. 但是我不知道该怎么办。 any suggestion or tutorial? 有什么建议或指导吗?

here is my code: 这是我的代码:

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    page=inflater.inflate(R.layout.activity_grc_page, container, false);
    page.setBackgroundResource(background_id);
    ((ImageView)page.findViewById(R.id.pagebackground)).setImageResource(background_id);
    ((ImageView)page.findViewById(R.id.pagebackground)).setScaleType(ImageView.ScaleType.CENTER_CROP);
    final ImageView background_view=((ImageView)page.findViewById(R.id.pagebackground));

    setBackground(background_path,background_id);

    return page;
}

public void setBackground(String path,int ires){
    if(path==null ){
        ((ImageView)page.findViewById(R.id.pagebackground)).setImageResource(ires);
        ((ImageView)page.findViewById(R.id.pagebackground)).setScaleType(ImageView.ScaleType.CENTER_CROP);
    }else{
        if(path.compareTo("")==0){
            ((ImageView)page.findViewById(R.id.pagebackground)).setImageResource(ires);
            ((ImageView)page.findViewById(R.id.pagebackground)).setScaleType(ImageView.ScaleType.CENTER_CROP);
        }else{
            if(path.indexOf("file://")==0){
                path=path.replace("file://", "");
            }
            File f = new File(path);
            if(f.exists()){
                Drawable d = Drawable.createFromPath(f.getAbsolutePath());
                ((ImageView)page.findViewById(R.id.pagebackground)).setImageDrawable(d);
                ((ImageView)page.findViewById(R.id.pagebackground)).setScaleType(ImageView.ScaleType.CENTER_CROP);
            }else{
                ((ImageView)page.findViewById(R.id.pagebackground)).setImageResource(ires);
                ((ImageView)page.findViewById(R.id.pagebackground)).setScaleType(ImageView.ScaleType.CENTER_CROP);
            }

        }

    }
}

You can use the concept of Lazy loading. 您可以使用延迟加载的概念。 In this way you UI will never get hanged and work smoothly..there are many tutorial available online you can check for that 通过这种方式,您的用户界面将永远不会挂死且无法正常工作。在线上有很多教程可供您检查

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM