Android 在 App State 中保存 ImageView

发布于 2024-11-15 22:20:46 字数 4087 浏览 0 评论 0原文

我制作了一个 Android 应用程序,它获取 XML 提要(从网站上),循环遍历它并显示提要中的图像。

我正在使用“图库”和“图像适配器”来显示所有图像 - 从网站加载它们(因为提要提供 URL)

但是当手机改变方向时,应用程序会重新设置自身并且状态会丢失 -导致提要再次被消耗并重新加载图像(这对带宽来说非常大)

在 ImageAdapter 中,我创建了一个 ImageView 对象数组,它允许我将从网站加载的图像保留在本地对象上(所以不要加载它们但

由于每次手机改变方向时都会重新设置应用程序,因此对象数组会被删除,所有内容都会再次加载备份。

我试图将这个 ImageView 数组保存在应用程序状态中,但找不到正确的函数???

这是代码:

package com.test;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.Toast;


public class ImageAdapter extends BaseAdapter {
    private Context mContext;

    private String[] mImageIds = {};
    private String[] titles = {};
    public ImageView[] images = {};

    public ImageAdapter(Context c) {
        mContext = c;

        try{
            //open local file and parse to XML  
            DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
            Document doc;

            doc = docBuilder.parse(mContext.openFileInput("xmlfeed.xml"));
            doc.getDocumentElement().normalize();

            NodeList itms = doc.getElementsByTagName("item");
            String temp = "";
            String tempTitles = "";

            //loop through xml items to retreive all nodes
            for (int i = 0; i < itms.getLength(); i++){
                Node itm = itms.item(i);
                if(temp==""){
                    temp = getTagValue(itm, "image");
                    tempTitles = getTagValue(itm, "title");
                }else{
                    temp = temp + "," + getTagValue(itm, "image");
                    tempTitles = tempTitles + "," + getTagValue(itm, "title");
                }
            }
            mImageIds = temp.split(",");
            titles = tempTitles.split(",");

            //create all images as empty vars
            if(images.length==0){
                images = new ImageView[itms.getLength()];
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

    public int getCount() {
        return mImageIds.length;
    }

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

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

    public View getView(int position, View convertView, ViewGroup parent) {
        //loads the image in case it does not already exists in the object
        if(images[position]==null){
            ImageView imgs = new ImageView(mContext);
            try{
                imgs.setImageDrawable(drawable_from_url(mImageIds[position], "src"));
            }catch(Exception e){
                e.printStackTrace();
            }
            imgs.setScaleType(ImageView.ScaleType.FIT_XY);
            images[position] = imgs;
        }
        return images[position];
    }

    Drawable drawable_from_url(String url, String src_name) throws java.net.MalformedURLException, java.io.IOException{
        Toast.makeText(mContext, url, Toast.LENGTH_SHORT).show();
        return Drawable.createFromStream(((java.io.InputStream)new java.net.URL(url).getContent()), src_name);
    }

    public String getTagValue(Node itm, String tagName){
        String title_value = "";
        if (itm.getNodeType() == Node.ELEMENT_NODE)
        {
            Element itmElm = (Element) itm;
            NodeList title = itmElm.getElementsByTagName(tagName);
            Element titleElm = (Element) title.item(0);
            NodeList title_nodes = titleElm.getChildNodes();
            title_value = ((Node) title_nodes.item(0)).getNodeValue().trim();
        }
        return title_value;
    }
}

请帮忙,我该如何将其保存在应用程序状态中???

I have made an Android App that gets an XML feed (off a website) loops through it and displays the images in the feed.

I am using a "Gallery" and an "Image Adapter" to display all images - loading them from the website (as the feed supplies a URL)

But when ever the phone changes oriantation the application re-sets itself and the state is lost - causing the feed to be consumed again and the images to be re-loaded (which is very big on the bandwidth)

In the ImageAdapter I have created an array of ImageView objects that allows me to retain the images loaded from the website on a local object (so not to load them again)

But since the application is re-set every time the phone changes orientation the object array gets erased and everything loads backup again.

I'm trying to save this ImageView array in the App State but can't find the right function???

Here is the code:

package com.test;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.Toast;


public class ImageAdapter extends BaseAdapter {
    private Context mContext;

    private String[] mImageIds = {};
    private String[] titles = {};
    public ImageView[] images = {};

    public ImageAdapter(Context c) {
        mContext = c;

        try{
            //open local file and parse to XML  
            DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
            Document doc;

            doc = docBuilder.parse(mContext.openFileInput("xmlfeed.xml"));
            doc.getDocumentElement().normalize();

            NodeList itms = doc.getElementsByTagName("item");
            String temp = "";
            String tempTitles = "";

            //loop through xml items to retreive all nodes
            for (int i = 0; i < itms.getLength(); i++){
                Node itm = itms.item(i);
                if(temp==""){
                    temp = getTagValue(itm, "image");
                    tempTitles = getTagValue(itm, "title");
                }else{
                    temp = temp + "," + getTagValue(itm, "image");
                    tempTitles = tempTitles + "," + getTagValue(itm, "title");
                }
            }
            mImageIds = temp.split(",");
            titles = tempTitles.split(",");

            //create all images as empty vars
            if(images.length==0){
                images = new ImageView[itms.getLength()];
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

    public int getCount() {
        return mImageIds.length;
    }

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

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

    public View getView(int position, View convertView, ViewGroup parent) {
        //loads the image in case it does not already exists in the object
        if(images[position]==null){
            ImageView imgs = new ImageView(mContext);
            try{
                imgs.setImageDrawable(drawable_from_url(mImageIds[position], "src"));
            }catch(Exception e){
                e.printStackTrace();
            }
            imgs.setScaleType(ImageView.ScaleType.FIT_XY);
            images[position] = imgs;
        }
        return images[position];
    }

    Drawable drawable_from_url(String url, String src_name) throws java.net.MalformedURLException, java.io.IOException{
        Toast.makeText(mContext, url, Toast.LENGTH_SHORT).show();
        return Drawable.createFromStream(((java.io.InputStream)new java.net.URL(url).getContent()), src_name);
    }

    public String getTagValue(Node itm, String tagName){
        String title_value = "";
        if (itm.getNodeType() == Node.ELEMENT_NODE)
        {
            Element itmElm = (Element) itm;
            NodeList title = itmElm.getElementsByTagName(tagName);
            Element titleElm = (Element) title.item(0);
            NodeList title_nodes = titleElm.getChildNodes();
            title_value = ((Node) title_nodes.item(0)).getNodeValue().trim();
        }
        return title_value;
    }
}

Please help, how would I go about saving this in the App State???

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

万水千山粽是情ミ 2024-11-22 22:20:46

这是因为您的列表视图是在 Activity A 的 oncreate() 方法中定义的。
对该活动执行以下操作,使 UIfreeze 处于屏幕方向

将以下内容添加到清单中的活动声明中:

android:configChanges="orientation"

所以看起来像

<activity android:label="@string/app_name" 
        android:configChanges="orientation|keyboardHidden" 
        android:name=".your.package">

问题是,当配置发生更改时,系统会销毁该活动。

谢谢
迪帕克

It is because your listview is defined inside oncreate() method of Activity A.
Do the followings to that activity to make your UIfreeze in screen orientation

Add the following to the activity declaration in the manifest:

android:configChanges="orientation"

so it looks like

<activity android:label="@string/app_name" 
        android:configChanges="orientation|keyboardHidden" 
        android:name=".your.package">

The matter is that the system destroys the activity when a change in the configuration occurs.

Thanks
Deepak

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文