关闭

android_26_AlphaListDemo

标签: androidSmartImageViewHttpURLConnectionSimpleAdapterXmlPullParser
131人阅读 评论(0) 收藏 举报
分类:

一个列表小案例,涉及到前面几个知识点:


HttpURLConnection 获取网络上的XML

XmlPullParser解析XML

SimpleAdapter展示数据(自定义item)

SmartImageView(第3方开源异步同步下载)


效果:


目录结构:


清单文件:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.sg31.alphalistview"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />

    // 注意权限 
    <uses-permission android:name="android.permission.INTERNET"/>
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>


布局文件:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.sg31.alphalistview.MainActivity" >

    <ListView 
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        ></ListView>

</RelativeLayout>



自定义item:

<?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="wrap_content" >
    
    <com.loopj.android.image.SmartImageView 
        android:id="@+id/imgView"
        android:layout_width="90dp"
        android:layout_height="70dp"
        android:src="@drawable/ic_launcher"
        android:layout_centerVertical="true"
        />
    <TextView 
        android:id="@+id/tv_roma"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="这是roma音"
        android:layout_toRightOf="@id/imgView"
        android:textSize="22sp"
        android:singleLine="true"
        />
	 <TextView 
	     android:id="@+id/tv_pingjiaming"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="这是平假名"
        android:layout_toRightOf="@id/imgView"
        android:layout_below="@id/tv_roma"
        android:textSize="15sp"
        android:textColor="@android:color/darker_gray"
        android:lines="2"
        />
	  <TextView 
	      android:id="@+id/tv_pianjiaming"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="这是片假名"
        android:textColor="#ff0000"
        android:layout_alignParentRight="true"
        android:layout_below="@id/tv_pingjiaming"
        />
</RelativeLayout>



模型类:

package com.sg31.alphalistview;

public class AlphaModel {

	private String roma;
	private String imgUrl;
	public String getImgUrl() {
		return imgUrl;
	}
	public void setImgUrl(String imgUrl) {
		this.imgUrl = imgUrl;
	}
	private String pingjiaming;
	private String pianjiaming;
	public String getRoma() {
		return roma;
	}
	public void setRoma(String roma) {
		this.roma = roma;
	}
	public String getPingjiaming() {
		return pingjiaming;
	}
	public void setPingjiaming(String pingjiaming) {
		this.pingjiaming = pingjiaming;
	}
	public String getPianjiaming() {
		return pianjiaming;
	}
	public void setPianjiaming(String pianjiaming) {
		this.pianjiaming = pianjiaming;
	}
	
}


主控制器:

package com.sg31.alphalistview;

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.loopj.android.image.SmartImageView;
import com.sg31.alphalistview.MainActivity;
import com.sg31.alphalistview.R;
import com.sg31.alphalistview.AlphaModel;

import com.sg31.alphalistview.MainActivity.SGBaseAdapter;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Xml;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity {

	List<AlphaModel> alphaList;

	Handler handler = new Handler() {
		// 更新界面
		public void handleMessage(android.os.Message msg) {
			ListView listView = (ListView) findViewById(R.id.listView);
			listView.setAdapter(new SGBaseAdapter());
		}
	};

	class SGBaseAdapter extends BaseAdapter {

		// 系统调用,用来获知集合中有多少条元素
		@Override
		public int getCount() {
			return alphaList.size();
		}

		// 由系统调用,获取一个View对象,作为ListView的条目
		// position:本次getView方法调用所返回的View对象,在listView中是处于第几个条目,那么position的值就是多少
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			AlphaModel p = alphaList.get(position);

			// 先从缓存池中取,取不到,new一个
			View v = convertView;
			CellViewHolder cellViewHolder = null;
			if (v != null) {
				cellViewHolder = (CellViewHolder) v.getTag();
			}

			// 判断条目是否有缓存
			if (v == null) {
				// 把布局文件填充成一个View对象
				v = View.inflate(MainActivity.this, R.layout.list_cell, null);

				// cell内部的控件也要缓存,通过资源id查找组件,注意调用的是View对象的findViewById
				cellViewHolder = new CellViewHolder();
				cellViewHolder.tv_roma = (TextView) v.findViewById(R.id.tv_roma);
				cellViewHolder.imgView = (SmartImageView) v.findViewById(R.id.imgView);
				cellViewHolder.tv_pingjiaming = (TextView) v.findViewById(R.id.tv_pingjiaming);
				cellViewHolder.tv_pianjiaming = (TextView) v
						.findViewById(R.id.tv_pianjiaming);
				// tip,通过tag绑定
				v.setTag(cellViewHolder);
			}

			cellViewHolder.tv_roma.setText(p.getRoma());
			cellViewHolder.tv_pingjiaming.setText(p.getPingjiaming());
			cellViewHolder.tv_pianjiaming.setText(p.getPianjiaming());
			//给新闻图片imageview设置内容
			cellViewHolder.imgView.setImageUrl(p.getImgUrl());
			return v;
		}

		@Override
		public Object getItem(int position) {
			return null;
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}

	}

	// 静态内部类,免去每次查找的烦恼,提升5%性能
	private static class CellViewHolder {
		private SmartImageView imgView;
		private TextView tv_roma;
		private TextView tv_pingjiaming;
		private TextView tv_pianjiaming;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		loadDataFromXML();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	public void loadDataFromXML() {
		Thread t = new Thread() {
			@Override
			public void run() {
				String path = "http://sg31.com/DemoAlphaList.xml";
				try {
					URL url = new URL(path);
					HttpURLConnection conn = (HttpURLConnection) url
							.openConnection();
					conn.setRequestMethod("GET");
					conn.setConnectTimeout(5000);
					conn.setReadTimeout(5000);
					// 发送http GET请求,获取相应码
					if (conn.getResponseCode() == 200) {
						InputStream is = conn.getInputStream();
						// 使用pull解析器,解析这个流
						parseAlphaXmlWithXmlPullParser(is);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		};
		t.start();
	}

	public void parseAlphaXmlWithXmlPullParser(InputStream is) {
		XmlPullParser xp = Xml.newPullParser();
		try {
			xp.setInput(is, "utf-8");
			// 对节点的事件类型进行判断,就可以知道当前节点是什么节点
			int type = xp.getEventType();
			AlphaModel model = null;
			while (type != XmlPullParser.END_DOCUMENT) {
				switch (type) {
				case XmlPullParser.START_TAG:
					if ("AlphaList".equals(xp.getName())) {
						alphaList = new ArrayList<AlphaModel>();
					} else if ("Alpha".equals(xp.getName())) {
						model = new AlphaModel();
					} else if ("roma".equals(xp.getName())) {
						String roma = xp.nextText();
						model.setRoma(roma);
					} else if ("pingjiaming".equals(xp.getName())) {
						String pingjiaming = xp.nextText();
						model.setPingjiaming(pingjiaming);
					} else if ("pianjiaming".equals(xp.getName())) {
						String pianjiaming = xp.nextText();
						model.setPianjiaming(pianjiaming);
					} else if ("imgUrl".equals(xp.getName())) {
						String imgUrl = xp.nextText();
						model.setImgUrl(imgUrl);
					}
					break;
				case XmlPullParser.END_TAG:
					if ("Alpha".equals(xp.getName())) {
						alphaList.add(model);
					}
					break;
				}
				// 解析完当前节点后,把指针移动至下一个节点,并返回它的事件类型
				type = xp.next();
			}
			// 发消息,让主线程设置listview的适配器,如果消息不需要携带数据,可以发送空消息
			handler.sendEmptyMessage(1);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}




0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:376563次
    • 积分:8535
    • 等级:
    • 排名:第2363名
    • 原创:472篇
    • 转载:2篇
    • 译文:0篇
    • 评论:75条
    最新评论