解析資料用ListView來展現,解析listview

來源:互聯網
上載者:User

解析資料用ListView來展現,解析listview

package com.org.demo.wangfeng;import java.io.InputStream;import java.net.HttpURLConnection;import java.net.URL;import java.util.ArrayList;import java.util.List;import org.xmlpull.v1.XmlPullParser;import com.org.demo.wangfeng.demo.News;import com.org.wangfeng.R;import android.annotation.SuppressLint;import android.app.Activity;import android.os.Bundle;import android.os.Handler;import android.util.Xml;import android.view.View;import android.view.ViewGroup;import android.widget.BaseAdapter;import android.widget.ListView;import android.widget.TextView;public class MainActivity extends Activity {    // 下載的地址    private String path = "";    List<News> newsList;    private ListView lv_main_list;    @SuppressLint("HandlerLeak")    Handler handler = new Handler() {        public void handleMessage(android.os.Message msg) {            lv_main_list.setAdapter(new MyAdapter());        };    };    @Override    protected void onCreate(Bundle savedInstanceState) {        // TODO Auto-generated method stub        super.onCreate(savedInstanceState);        setContentView(R.layout.main);        getNewInfo();        lv_main_list = (ListView) findViewById(R.id.lv_main_list);        // 要保證在設定適配器時,新聞xml檔案已經解析完畢        // lv_main_list.setAdapter(new MyAdapter());    }/** * 設定lv_main_list適配器 * @author Administrator * */    private class MyAdapter extends BaseAdapter {        // 得到模型曾中元素的數量,用來確定ListView需要有多少個條目        @Override        public int getCount() {            // TODO Auto-generated method stub            return newsList.size();        }        // 返回一個View對象,作為ListView的條目顯示至介面        @Override        public View getView(int positon, View convertView, ViewGroup parent) {            News newss = newsList.get(positon);            View v;            ViewHolder myHolder;            if (convertView == null) {                v = View.inflate(MainActivity.this, R.layout.mainlist_item,                        null);                myHolder = new ViewHolder();                // 把布局檔案中所有組件的對象封裝至ViewHolder對象中                myHolder.tv_title = (TextView) v                        .findViewById(R.id.tv_main_title);                myHolder.tv_detail = (TextView) v                        .findViewById(R.id.tv_main_detail);                myHolder.tv_comment = (TextView) v                        .findViewById(R.id.tv_main_comment);                // 把ViewHolder對象封裝至View對象中                v.setTag(myHolder);            } else {                v = convertView;                myHolder = (ViewHolder) v.getTag();            }            // TODO Auto-generated method stub            // 給三個文字框設定內容            myHolder.tv_title.setText(newss.getTitle());            myHolder.tv_detail.setText(newss.getDetail());            myHolder.tv_comment.setText(newss.getComment() + "條評論");            // 給新聞圖片imageview設定內容            return v;        }        class ViewHolder {            // 條目的布局檔案中有什麼組件,這裡就定義什麼組件            TextView tv_title;            TextView tv_detail;            TextView tv_comment;        }        @Override        public Object getItem(int arg0) {            // TODO Auto-generated method stub            return null;        }        @Override        public long getItemId(int arg0) {            // TODO Auto-generated method stub            return 0;        }    }    private void getNewInfo() {        // TODO Auto-generated method stub        Thread t = new Thread() {            @Override            public void run() {                try {                    URL url = new URL(path);                    HttpURLConnection conn = (HttpURLConnection) url                            .openConnection();                    conn.setRequestMethod("GET");                    conn.setConnectTimeout(5000);                    conn.setReadTimeout(5000);                    conn.connect();                    if (conn.getResponseCode() == 200) {                        // 伺服器返回的流                        InputStream is = conn.getInputStream();                        // 使用pull解析器來解析流                        parseNewsXml(is);                    }                } catch (Exception e) {                    // TODO Auto-generated catch block                    e.printStackTrace();                }            }        };        t.start();    }    /** 解析xml */    private void parseNewsXml(InputStream is) {        XmlPullParser xp = Xml.newPullParser();        try {            xp.setInput(is, "utf_8");            // 對節點的事件類型進行判斷就可以知道當期節點是什麼節點            int type = xp.getEventType();            News news = null;            while (type != XmlPullParser.END_DOCUMENT) {                switch (type) {                case XmlPullParser.START_TAG:                    if ("newslist".equals(xp.getName())) {                        newsList = new ArrayList<News>();                    } else if ("news".equals(xp.getName())) {                        news = new News();                    } else if ("title".equals(xp.getName())) {                        String title = xp.nextText();                        news.setTitle(title);                    } else if ("detail".equals(xp.getName())) {                        String detail = xp.nextText();                        news.setDetail(detail);                    } else if ("comment".equals(xp.getName())) {                        String comment = xp.nextText();                        news.setComment(comment);                    } else if ("imageUrl".equals(xp.getName())) {                        String imageUrl = xp.nextText();                        news.setImageUrl(imageUrl);                    }                    break;                case XmlPullParser.END_TAG:                    if ("news".equals(xp.getName())) {                        newsList.add(news);                    }                    break;                }                // 解析完當期的節點後,把指標移動至下個節點,並返回它的事件類型                type = xp.next();            }            for (News i : newsList) {                System.out.println(i.toString());            }            // 發訊息,讓主線程設定ListView的適配器,如果訊息不需要攜帶資料的話可以發送個空訊息            handler.sendEmptyMessage(1);// 資料1 表示訊息發送成功的意思        } catch (Exception e) {            // TODO Auto-generated catch block            e.printStackTrace();        }    }}

 

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent" >    <ImageView        android:id="@+id/iv_main_image"        android:layout_width="70dp"        android:layout_height="85dp"        android:contentDescription="@null"        android:paddingBottom="2dp"        android:paddingTop="3dp"        android:scaleType="fitXY"        android:src="@drawable/d" />    <TextView        android:id="@+id/tv_main_title"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_toRightOf="@id/iv_main_image"        android:singleLine="true"        android:text="這是大標題"        android:textSize="23sp" />    <TextView        android:id="@+id/tv_main_detail"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_below="@id/iv_main_image"        android:layout_toRightOf="@id/iv_main_image"        android:lines="2"        android:text="這是本文"        android:textColor="@android:color/darker_gray"        android:textSize="14sp" />    <TextView        android:id="@+id/tv_main_comment"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignParentRight="true"        android:layout_below="@id/tv_main_detail"        android:text="評論書"        android:textColor="#ff0000" /></RelativeLayout>

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.