帮助在列表视图中混合文本和图像

发布于 2024-11-06 22:20:13 字数 10628 浏览 0 评论 0原文

我的应用程序正在从网页上的 Xml 文件中获取数据。该日期放置在列表视图中。在 XML 文件中,每个项目都有一个图像链接。我需要一些帮助来找出将 xml 文件中的图像与文本一起放入 listView 的最简单方法。

现在,在我的代码中,我刚刚在布局文件的 android:src ="" 中放置了一个静态图像。

屏幕截图:

在此处输入图像描述

xmlfile:

http://roskilde-festival.dk/typo3conf/ext/tcpageheaderobjects/xml/bandobjects_251_uk.xml

MainClass:

package com.bandreminder;

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

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

import android.app.ListActivity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

public class bandR extends ListActivity {

    private ConnectivityManager connMgr;

    private android.net.NetworkInfo network_info;
    private boolean blnNetworkAccess=false;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.listplaceholder);



        connMgr = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
        network_info = connMgr.getActiveNetworkInfo();

        if(network_info != null && network_info.isConnectedOrConnecting()) {
            blnNetworkAccess = true;
        }

       if(blnNetworkAccess) {


        fetchData();

        }
        else {
            Toast.makeText(bandR.this, "No Internet connection, please enable", Toast.LENGTH_LONG).show();
        }
    }

    public void onResume(){
        super.onResume();
        if(network_info != null && network_info.isConnectedOrConnecting()) {
            Log.w("resume", ""+network_info);
        }

        else {
            Toast.makeText(bandR.this, "No Internet connection, please enable", Toast.LENGTH_LONG).show();
        }
    }

    public void onPause(){
        super.onPause();
        blnNetworkAccess = false;
        Log.w("onPause", "test");
    }


    private void fetchData() {



        ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
        Integer numResults;
        String xml = XmlHandler.getXML();

        Document doc = XmlHandler.XMLfromString(xml);

        numResults = XmlHandler.numResults(doc);


         if((numResults <= 0)){
            Toast.makeText(bandR.this, "No Bands found", Toast.LENGTH_LONG).show();  
            finish();
         }

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

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

            Element e = (Element)nodes.item(i);
            map.put("artistName", "Artist Name: "+ XmlHandler.getValue(e, "artistName"));
            map.put("country", "Country: " + XmlHandler.getValue(e, "country"));

            map.put("scene", "Scene: " + XmlHandler.getValue(e, "scene"));
            map.put("tidspunkt", "Tidspunkt: " + XmlHandler.getValue(e, "tidspunkt"));


            mylist.add(map);            
        }       


         ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.main, 
                         new String[] { "artistName", "country", "scene","tidspunkt" }, 
                         new int[] { R.id.item_artistname, R.id.item_country,R.id.scene ,R.id.tidspunkt});

         setListAdapter(adapter);




         final ListView lv = getListView();
         lv.setTextFilterEnabled(true); 
         lv.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {              
                @SuppressWarnings("unchecked")
                HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);                   
                Toast.makeText(bandR.this, "artistName '" + o.get("artistName") + "' was clicked.", Toast.LENGTH_LONG).show(); 

            }
        });
    }



}

XMLHandler 类:

package com.bandreminder;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.URL;
import java.net.URLConnection;

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

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;

import android.util.Log;


public class XmlHandler{

    public static boolean connected;

public boolean getConnected(){

        return connected;

    }

    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 = null;
         if( elem != null){
             if (elem.hasChildNodes()){
                 for( kid = elem.getFirstChild(); kid != null; kid = kid.getNextSibling() ){
                     if( kid.getNodeType() == Node.TEXT_NODE  ){
                         return kid.getNodeValue();
                     }
                 }
             }
             else

                 return  elem.getNodeValue();
         }
         return "";
     }

     public static String getXML(){
        ;
            String line = null;
            StringBuilder result = new StringBuilder();
            try {
                // Send data
                URL url = new URL("http://roskilde-festival.dk/typo3conf/ext/tcpageheaderobjects/xml/bandobjects_251_uk.xml");
                URLConnection conn = url.openConnection();
                conn.setDoOutput(true);
                // Get the response
                BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                while((line = rd.readLine()) != null){
                    result.append(line);
                }
                //Close
                rd.close();
            } catch (Exception e){
                connected = false;

            }

            return result.toString();
    }

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

        int res = -1;



        try{

            res += results.getChildNodes().getLength();




        }catch(Exception e ){

            Log.w("Exception numresults", ""+e.getMessage());
            res = -1;
        }
        Log.w("numres", ""+String.valueOf(res));
        return res-1;
    }

    public static String getValue(Element item, String str) {       
        NodeList n = item.getElementsByTagName(str);
        Log.w("element", ""+n.item(0).getTextContent());

        //return XmlHandler.getElementValue(n.item(0));
        return n.item(0).getTextContent();
    }



}

布局:

listplaceholder:

<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">    

    <ListView
        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/android:empty"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="No data"/>

</LinearLayout>

主布局:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="7dp"
    android:id="@+id/layout"
    >
<TextView  
    android:id="@+id/item_artistname"

    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:padding="2dp"
    android:textSize="15dp" />
<TextView  
    android:id="@+id/item_country"
    android:layout_below="@id/item_artistname"
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:padding="2dp"
    android:textSize="13dp" />
<TextView  
    android:id="@+id/scene"
    android:layout_below="@id/item_country"
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:padding="2dp"
    android:textSize="13dp" />
<TextView  
    android:id="@+id/tidspunkt"
    android:layout_below="@id/scene"
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:padding="2dp"
    android:textSize="13dp" />

<ImageView
    android:id="@+id/img"

    android:layout_below="@id/item_artistname"
    android:layout_alignParentRight="true"
    android:src="@drawable/abe"

    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>

</RelativeLayout>

My application is fetching data from a Xml file on a webpage. That date is placed in a listView. In the XML file there is a link to a image for every item. I need some help figuring out the easiest way to get that image from the xml file into the listView together with the text.

In my code right now i have just placed a static image in the android:src ="" in the layout file.

Screenshot:

enter image description here

xmlfile:

http://roskilde-festival.dk/typo3conf/ext/tcpageheaderobjects/xml/bandobjects_251_uk.xml

MainClass:

package com.bandreminder;

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

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

import android.app.ListActivity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

public class bandR extends ListActivity {

    private ConnectivityManager connMgr;

    private android.net.NetworkInfo network_info;
    private boolean blnNetworkAccess=false;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.listplaceholder);



        connMgr = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
        network_info = connMgr.getActiveNetworkInfo();

        if(network_info != null && network_info.isConnectedOrConnecting()) {
            blnNetworkAccess = true;
        }

       if(blnNetworkAccess) {


        fetchData();

        }
        else {
            Toast.makeText(bandR.this, "No Internet connection, please enable", Toast.LENGTH_LONG).show();
        }
    }

    public void onResume(){
        super.onResume();
        if(network_info != null && network_info.isConnectedOrConnecting()) {
            Log.w("resume", ""+network_info);
        }

        else {
            Toast.makeText(bandR.this, "No Internet connection, please enable", Toast.LENGTH_LONG).show();
        }
    }

    public void onPause(){
        super.onPause();
        blnNetworkAccess = false;
        Log.w("onPause", "test");
    }


    private void fetchData() {



        ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
        Integer numResults;
        String xml = XmlHandler.getXML();

        Document doc = XmlHandler.XMLfromString(xml);

        numResults = XmlHandler.numResults(doc);


         if((numResults <= 0)){
            Toast.makeText(bandR.this, "No Bands found", Toast.LENGTH_LONG).show();  
            finish();
         }

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

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

            Element e = (Element)nodes.item(i);
            map.put("artistName", "Artist Name: "+ XmlHandler.getValue(e, "artistName"));
            map.put("country", "Country: " + XmlHandler.getValue(e, "country"));

            map.put("scene", "Scene: " + XmlHandler.getValue(e, "scene"));
            map.put("tidspunkt", "Tidspunkt: " + XmlHandler.getValue(e, "tidspunkt"));


            mylist.add(map);            
        }       


         ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.main, 
                         new String[] { "artistName", "country", "scene","tidspunkt" }, 
                         new int[] { R.id.item_artistname, R.id.item_country,R.id.scene ,R.id.tidspunkt});

         setListAdapter(adapter);




         final ListView lv = getListView();
         lv.setTextFilterEnabled(true); 
         lv.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {              
                @SuppressWarnings("unchecked")
                HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);                   
                Toast.makeText(bandR.this, "artistName '" + o.get("artistName") + "' was clicked.", Toast.LENGTH_LONG).show(); 

            }
        });
    }



}

XMLHandler Class:

package com.bandreminder;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.URL;
import java.net.URLConnection;

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

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;

import android.util.Log;


public class XmlHandler{

    public static boolean connected;

public boolean getConnected(){

        return connected;

    }

    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 = null;
         if( elem != null){
             if (elem.hasChildNodes()){
                 for( kid = elem.getFirstChild(); kid != null; kid = kid.getNextSibling() ){
                     if( kid.getNodeType() == Node.TEXT_NODE  ){
                         return kid.getNodeValue();
                     }
                 }
             }
             else

                 return  elem.getNodeValue();
         }
         return "";
     }

     public static String getXML(){
        ;
            String line = null;
            StringBuilder result = new StringBuilder();
            try {
                // Send data
                URL url = new URL("http://roskilde-festival.dk/typo3conf/ext/tcpageheaderobjects/xml/bandobjects_251_uk.xml");
                URLConnection conn = url.openConnection();
                conn.setDoOutput(true);
                // Get the response
                BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                while((line = rd.readLine()) != null){
                    result.append(line);
                }
                //Close
                rd.close();
            } catch (Exception e){
                connected = false;

            }

            return result.toString();
    }

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

        int res = -1;



        try{

            res += results.getChildNodes().getLength();




        }catch(Exception e ){

            Log.w("Exception numresults", ""+e.getMessage());
            res = -1;
        }
        Log.w("numres", ""+String.valueOf(res));
        return res-1;
    }

    public static String getValue(Element item, String str) {       
        NodeList n = item.getElementsByTagName(str);
        Log.w("element", ""+n.item(0).getTextContent());

        //return XmlHandler.getElementValue(n.item(0));
        return n.item(0).getTextContent();
    }



}

Layout:

listplaceholder:

<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">    

    <ListView
        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/android:empty"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="No data"/>

</LinearLayout>

main layout:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="7dp"
    android:id="@+id/layout"
    >
<TextView  
    android:id="@+id/item_artistname"

    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:padding="2dp"
    android:textSize="15dp" />
<TextView  
    android:id="@+id/item_country"
    android:layout_below="@id/item_artistname"
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:padding="2dp"
    android:textSize="13dp" />
<TextView  
    android:id="@+id/scene"
    android:layout_below="@id/item_country"
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:padding="2dp"
    android:textSize="13dp" />
<TextView  
    android:id="@+id/tidspunkt"
    android:layout_below="@id/scene"
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:padding="2dp"
    android:textSize="13dp" />

<ImageView
    android:id="@+id/img"

    android:layout_below="@id/item_artistname"
    android:layout_alignParentRight="true"
    android:src="@drawable/abe"

    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>

</RelativeLayout>

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

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

发布评论

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

评论(1

年少掌心 2024-11-13 22:20:13

您的 xml 文件中有图像 url。像提取其他值一样提取 url。
您必须实现自己的适配器,它将加载图像并将它们绑定到行中的图像视图。

有加载图像的答案:
ListView 中的图像延迟加载

You have image urls in xml file. Extract the urls like you do with other values.
You must to implement your own adapter which will load images and bind them to image view in rows.

There is answer for loading images:
Lazy load of images in ListView

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