在 Android 中通过后台显示 XML 数据

发布于 2024-11-15 09:20:03 字数 7155 浏览 0 评论 0原文

当我在 Android 应用程序中显示 XML 数据列表时,它会显示每个项目都有自己的背景。但我希望背景图像是静态的,并且列表显示在它上面。下面是 listplaceholder.xml 和两个活动的代码。一个包含 XML 函数,另一个用于显示数据。

您还可以在此处下载 eclipse 页面

listplaceholder.xml:

<ListView
    android:background="#00000000"
    android:id="@id/android:list"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:drawSelectorOnTop="false" />

      <TextView  
android:id="@+id/item_title"
android:layout_width="fill_parent" 
android:layout_height="wrap_content" 
android:textAppearance="?android:attr/textAppearanceMedium"
android:background="#00000000"
android:padding="2dp"
android:textSize="20dp" />
<TextView  
android:id="@+id/item_subtitle"
android:layout_width="fill_parent" 
android:layout_height="wrap_content"
android:background="#00000000" 
android:padding="2dp"
android:textSize="13dp" />
<TextView  
android:id="@+id/id_title"
android:layout_width="fill_parent" 
android:layout_height="wrap_content" 
android:background="#00000000"
android:padding="2dp"
android:textSize="13dp" />

Xmlfunctions:

package com.patriotsar;

import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;

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

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;


public class XMLfunctions {

    public final static Document XMLfromString(String xml){

        Document doc = null;

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        try {

            DocumentBuilder db = dbf.newDocumentBuilder();

            InputSource is = new InputSource();
            is.setCharacterStream(new StringReader(xml));
            doc = db.parse(is); 

        } catch (ParserConfigurationException e) {
            System.out.println("XML parse error: " + e.getMessage());
            return null;
        } catch (SAXException e) {
            System.out.println("Wrong XML file structure: " + e.getMessage());
            return null;
        } catch (IOException e) {
            System.out.println("I/O exeption: " + e.getMessage());
            return null;
        }

        return doc;

    }

    /** Returns element value
      * @param elem element (it is XML tag)
      * @return Element value otherwise empty String
      */
     public final static String getElementValue( Node elem ) {
         Node kid;
         if( elem != null){
             if (elem.hasChildNodes()){
                 for( kid = elem.getFirstChild(); kid != null; kid = kid.getNextSibling() ){
                     if( kid.getNodeType() == Node.TEXT_NODE  ){
                         return kid.getNodeValue();
                     }
                 }
             }
         }
         return "";
     }

     public static String getXML(){  
            String line = null;

            try {

                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost("http://p-xr.com/xml");

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                line = EntityUtils.toString(httpEntity);

            } catch (UnsupportedEncodingException e) {
                line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
            } catch (MalformedURLException e) {
                line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
            } catch (IOException e) {
                line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
            }

            return line;

    }

    public static int numResults(Document doc){     
        Node results = doc.getDocumentElement();
        int res = -1;

        try{
            res = Integer.valueOf(results.getAttributes().getNamedItem("count").getNodeValue());
        }catch(Exception e ){
            res = -1;
        }

        return res;
    }

    public static String getValue(Element item, String str) {       
        NodeList n = item.getElementsByTagName(str);        
        return XMLfunctions.getElementValue(n.item(0));
    }
}

ShowXMLPAR.java:

package com.patriotsar;

import java.util.ArrayList;
import java.util.HashMap;

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

import com.patriotsar.XMLfunctions;


import android.app.ListActivity;


import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class ShowXMLPAR extends ListActivity {

     /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.listplaceholder);

        ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();


        String xml = XMLfunctions.getXML();
        Document doc = XMLfunctions.XMLfromString(xml);

        int numResults = XMLfunctions.numResults(doc);

        if((numResults <= 0)){
            Toast.makeText(ShowXMLPAR.this, "Geen resultaten gevonden", Toast.LENGTH_LONG).show();  
            finish();
        }

        NodeList nodes = doc.getElementsByTagName("result");

        for (int i = 0; i < nodes.getLength(); i++) {                           
            HashMap<String, String> map = new HashMap<String, String>();    

            Element e = (Element)nodes.item(i);
            map.put("id","test:" +  XMLfunctions.getValue(e, "id"));
            map.put("name", "MIKE RAWERS:" + XMLfunctions.getValue(e, "name"));
            map.put("Score", "Score: " + XMLfunctions.getValue(e, "score"));
            mylist.add(map);            
        }       
//       
        ListAdapter adapter = new SimpleAdapter(ShowXMLPAR.this, mylist , R.layout.listplaceholder, 
                        new String[] { "id", "name", "Score" }, 
                        new int[] { R.id.id_title, R.id.item_title, R.id.item_subtitle });

        setListAdapter(adapter);


}
}

When I show my list of XML data in my android app it shows each item with its own background. But I want the background image to be static and the list to show over it. below is the code for the listplaceholder.xml and the two activities. One has the XML functions in it and the other to show the data.

You can also downloaw the eclipse page here

listplaceholder.xml:

<ListView
    android:background="#00000000"
    android:id="@id/android:list"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:drawSelectorOnTop="false" />

      <TextView  
android:id="@+id/item_title"
android:layout_width="fill_parent" 
android:layout_height="wrap_content" 
android:textAppearance="?android:attr/textAppearanceMedium"
android:background="#00000000"
android:padding="2dp"
android:textSize="20dp" />
<TextView  
android:id="@+id/item_subtitle"
android:layout_width="fill_parent" 
android:layout_height="wrap_content"
android:background="#00000000" 
android:padding="2dp"
android:textSize="13dp" />
<TextView  
android:id="@+id/id_title"
android:layout_width="fill_parent" 
android:layout_height="wrap_content" 
android:background="#00000000"
android:padding="2dp"
android:textSize="13dp" />

Xmlfunctions:

package com.patriotsar;

import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;

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

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;


public class XMLfunctions {

    public final static Document XMLfromString(String xml){

        Document doc = null;

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        try {

            DocumentBuilder db = dbf.newDocumentBuilder();

            InputSource is = new InputSource();
            is.setCharacterStream(new StringReader(xml));
            doc = db.parse(is); 

        } catch (ParserConfigurationException e) {
            System.out.println("XML parse error: " + e.getMessage());
            return null;
        } catch (SAXException e) {
            System.out.println("Wrong XML file structure: " + e.getMessage());
            return null;
        } catch (IOException e) {
            System.out.println("I/O exeption: " + e.getMessage());
            return null;
        }

        return doc;

    }

    /** Returns element value
      * @param elem element (it is XML tag)
      * @return Element value otherwise empty String
      */
     public final static String getElementValue( Node elem ) {
         Node kid;
         if( elem != null){
             if (elem.hasChildNodes()){
                 for( kid = elem.getFirstChild(); kid != null; kid = kid.getNextSibling() ){
                     if( kid.getNodeType() == Node.TEXT_NODE  ){
                         return kid.getNodeValue();
                     }
                 }
             }
         }
         return "";
     }

     public static String getXML(){  
            String line = null;

            try {

                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost("http://p-xr.com/xml");

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                line = EntityUtils.toString(httpEntity);

            } catch (UnsupportedEncodingException e) {
                line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
            } catch (MalformedURLException e) {
                line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
            } catch (IOException e) {
                line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
            }

            return line;

    }

    public static int numResults(Document doc){     
        Node results = doc.getDocumentElement();
        int res = -1;

        try{
            res = Integer.valueOf(results.getAttributes().getNamedItem("count").getNodeValue());
        }catch(Exception e ){
            res = -1;
        }

        return res;
    }

    public static String getValue(Element item, String str) {       
        NodeList n = item.getElementsByTagName(str);        
        return XMLfunctions.getElementValue(n.item(0));
    }
}

ShowXMLPAR.java:

package com.patriotsar;

import java.util.ArrayList;
import java.util.HashMap;

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

import com.patriotsar.XMLfunctions;


import android.app.ListActivity;


import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class ShowXMLPAR extends ListActivity {

     /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.listplaceholder);

        ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();


        String xml = XMLfunctions.getXML();
        Document doc = XMLfunctions.XMLfromString(xml);

        int numResults = XMLfunctions.numResults(doc);

        if((numResults <= 0)){
            Toast.makeText(ShowXMLPAR.this, "Geen resultaten gevonden", Toast.LENGTH_LONG).show();  
            finish();
        }

        NodeList nodes = doc.getElementsByTagName("result");

        for (int i = 0; i < nodes.getLength(); i++) {                           
            HashMap<String, String> map = new HashMap<String, String>();    

            Element e = (Element)nodes.item(i);
            map.put("id","test:" +  XMLfunctions.getValue(e, "id"));
            map.put("name", "MIKE RAWERS:" + XMLfunctions.getValue(e, "name"));
            map.put("Score", "Score: " + XMLfunctions.getValue(e, "score"));
            mylist.add(map);            
        }       
//       
        ListAdapter adapter = new SimpleAdapter(ShowXMLPAR.this, mylist , R.layout.listplaceholder, 
                        new String[] { "id", "name", "Score" }, 
                        new int[] { R.id.id_title, R.id.item_title, R.id.item_subtitle });

        setListAdapter(adapter);


}
}

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

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

发布评论

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

评论(1

德意的啸 2024-11-22 09:20:03

尝试将 android:background="#00000000" 添加到 ListView 标记。这应该将背景设置为透明并允许 LinearLayout 背景显示出来。您可能需要对每个 TextView 执行相同的操作。

巴里

Try adding android:background="#00000000" to the ListView tag. This should set the background to transparent and allow the LinearLayout background to show through. You may need to do the same thing with each TextView.

Barry

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