Android核心基础(五)
1、仿网易新闻客户端
<LinearLayout 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:orientation="vertical"
tools:context=".MainActivity" >
<TextView
android:layout_width="fill_parent"
android:layout_height="54dip"
android:background="#ff0000"
android:gravity="center_vertical"
android:text="网易新闻"
android:textColor="#ffffff"
android:textSize="24sp" />
<FrameLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<LinearLayout
android:id="@+id/ll_loading"
android:visibility="invisible"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:orientation="vertical" >
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="正在加载数据..." />
</LinearLayout>
<ListView
android:id="@+id/lv_news"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
</ListView>
</FrameLayout>
</LinearLayout>
<?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="85dip" >
<com.loopj.android.image.SmartImageView
android:id="@+id/iv_icon"
android:layout_width="72dip"
android:layout_height="53dp"
android:layout_marginLeft="5dip"
android:layout_marginTop="15dip"
android:src="@drawable/a" />
<TextView
android:singleLine="true"
android:id="@+id/tv_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="8dip"
android:layout_marginTop="10dip"
android:layout_toRightOf="@id/iv_icon"
android:text="我是标题,阿打发打发的发生打发打发打发撒发生大法"
android:textColor="#000000"
android:textSize="18sp" />
<TextView
android:id="@+id/tv_description"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/tv_title"
android:layout_marginLeft="8dip"
android:layout_marginTop="1dip"
android:layout_toRightOf="@id/iv_icon"
android:lines="2"
android:text="我是描述哈哈哈哈哈哈哈,嘎嘎嘎嘎嘎嘎,大开发商电缆附件啊赛罗克就分啦kdj阿飞爱的发放时大法师打法大发生地"
android:textColor="#AA000000"
android:textSize="12sp" />
<TextView
android:id="@+id/tv_type"
android:layout_below="@id/tv_description"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="评论:333个"
android:textColor="#000000"
android:layout_alignParentRight="true"
android:layout_alignParentBottom="true"
/>
</RelativeLayout>
package com.itheima.news;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.itheima.news.domain.NewsInfo;
import com.itheima.news.service.NewsInfoParser;
import com.loopj.android.image.SmartImageView;
public class MainActivity extends Activity {
protected static final int LOAD_ERROR = 1;
protected static final int SET_ADAPTER = 2;
private ListView lv_news;
private List<NewsInfo> newsInfos;
private LinearLayout ll_loading;
private Handler handler = new Handler(){
public void handleMessage(android.os.Message msg) {
//加载数据后 设置界面不可见
ll_loading.setVisibility(View.INVISIBLE);
switch (msg.what) {
case LOAD_ERROR:
Toast.makeText(getApplicationContext(), "加载数据失败", 0).show();
break;
case SET_ADAPTER:
lv_news.setAdapter(new NewsAdapter());
break;
}
};
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
lv_news = (ListView) findViewById(R.id.lv_news);
ll_loading = (LinearLayout) findViewById(R.id.ll_loading);
getData();
// lv_news.setAdapter(adapter);
}
/**
* 连接服务器 获取服务器上新闻数据
*/
private void getData() {
//加载数据前 设置界面可见
ll_loading.setVisibility(View.VISIBLE);
new Thread(){
public void run() {
try {
URL url = new URL(getString(R.string.serverurl));
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
int code = conn.getResponseCode();
if(code == 200){
//xml文件的流
InputStream is = conn.getInputStream();
//模拟一个很慢的网络.. 睡眠一段时间
Thread.sleep(3000);
newsInfos = NewsInfoParser.getNewsInfos(is);
//设置数据适配器了.
Message msg = new Message();
msg.what = SET_ADAPTER;
handler.sendMessage(msg);
}else{
Message msg = new Message();
msg.what = LOAD_ERROR;
handler.sendMessage(msg);
}
} catch (Exception e) {
e.printStackTrace();
Message msg = new Message();
msg.what = LOAD_ERROR;
handler.sendMessage(msg);
}
};
}.start();
}
private class NewsAdapter extends BaseAdapter{
@Override
public int getCount() {
return newsInfos.size();
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = View.inflate(getApplicationContext(), R.layout.list_item, null);
TextView tv_title = (TextView) view.findViewById(R.id.tv_title);
TextView tv_description = (TextView) view.findViewById(R.id.tv_description);
TextView tv_type = (TextView)view.findViewById(R.id.tv_type);
NewsInfo info = newsInfos.get(position);
tv_title.setText(info.getTitle());
tv_description.setText(info.getDescription());
SmartImageView siv = (SmartImageView) view.findViewById(R.id.iv_icon);
siv.setImageUrl(info.getImage(), R.drawable.ic_launcher, R.drawable.ic_launcher);
int type = info.getType();
switch (type) {
case 1://一般的新闻 有评论个数
tv_type.setText("评论:"+info.getComment());
break;
case 2:
tv_type.setText("专题");
tv_type.setBackgroundColor(Color.RED);
break;
case 3:
tv_type.setText("LIVE");
tv_type.setBackgroundColor(Color.BLUE);
break;
}
return view;
}
}
}
package com.itheima.news.domain;
public class NewsInfo {
private String title;
private String description;
private String image;
private int type;
private int comment;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public int getComment() {
return comment;
}
public void setComment(int comment) {
this.comment = comment;
}
@Override
public String toString() {
return "NewsInfo [title=" + title + ", description=" + description
+ ", image=" + image + ", type=" + type + ", comment="
+ comment + "]";
}
}
package com.itheima.news.service;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import android.util.Xml;
import com.itheima.news.domain.NewsInfo;
public class NewsInfoParser {
/**
* 解析xml文件的流 获取全部的新闻信息
*
* @param is
* @return 新闻信息的集合 null代表解析失败
*/
public static List<NewsInfo> getNewsInfos(InputStream is) {
try {
List<NewsInfo> newsInfos = null;
NewsInfo newsInfo = null;
XmlPullParser parser = Xml.newPullParser();
parser.setInput(is, "UTF-8");
int enventType = parser.getEventType();
while (enventType != XmlPullParser.END_DOCUMENT) {
switch (enventType) {
case XmlPullParser.START_TAG:
if ("channel".equals(parser.getName())) {
newsInfos = new ArrayList<NewsInfo>();
} else if ("item".equals(parser.getName())) {
newsInfo = new NewsInfo();
} else if ("title".equals(parser.getName())) {
String title = parser.nextText();
newsInfo.setTitle(title);
} else if ("description".equals(parser.getName())) {
String description = parser.nextText();
newsInfo.setDescription(description);
} else if ("image".equals(parser.getName())) {
String image = parser.nextText();
newsInfo.setImage(image);
} else if ("type".equals(parser.getName())) {
String type = parser.nextText();
newsInfo.setType(Integer.parseInt(type));
} else if ("comment".equals(parser.getName())) {
String comment = parser.nextText();
newsInfo.setComment(Integer.parseInt(comment));
}
break;
case XmlPullParser.END_TAG:
if ("item".equals(parser.getName())) {
newsInfos.add(newsInfo);
newsInfo = null;
}
break;
}
enventType = parser.next();// 继续解析下一个节点
}
return newsInfos;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
2、文件的上传
package com.itheima.upload;
import java.io.File;
import java.io.FileNotFoundException;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
private EditText et_path;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_path = (EditText) findViewById(R.id.et_path);
}
public void upload(View view) {
String path = et_path.getText().toString().trim();
if (TextUtils.isEmpty(path)) {
Toast.makeText(this, "路径不能为空", 1).show();
return;
}
File file = new File(path);
if (file.exists() && file.length() > 0) {
AsyncHttpClient client = new AsyncHttpClient();
// 指定上传一个文件
RequestParams params = new RequestParams();
try {
params.put("filename", file);
} catch (FileNotFoundException e) {
e.printStackTrace();
} // Upload a File
client.post("http://192.168.1.100:8080/web/UploadFileServlet",
params, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(String content) {
super.onSuccess(content);
Toast.makeText(getApplicationContext(), "上传成功", 0)
.show();
}
@Override
public void onFailure(Throwable error, String content) {
super.onFailure(error, content);
Toast.makeText(getApplicationContext(), "上传失败", 0)
.show();
}
});
} else {
Toast.makeText(this, "文件不存在,或者大小为0", 1).show();
return;
}
}
}
3、SmartView工作原理
package com.itheima.smartimageview;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SmartImageView siv = (SmartImageView) findViewById(R.id.siv);
siv.setImageUrl("http://192.168.1.100:8089/tomcat.png",R.drawable.ic_launcher);
}
}
package com.itheima.smartimageview;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
public class ImageUtils {
/**
* 获取一个路径的bitmap
*
* @param iconpath
* @return 图片获取失败 返回 null
*/
public static Bitmap getUrlBitmap(String iconpath) {
try {
URL url = new URL(iconpath);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
int code = conn.getResponseCode();
if (code == 200) {
return BitmapFactory.decodeStream(conn.getInputStream());
} else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
package com.itheima.smartimageview;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.widget.ImageView;
public class SmartImageView extends ImageView {
protected static final int LOAD_SUCCESS = 1;
protected static final int LOAD_ERROR = 2;
private Handler handler = new Handler(){
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case LOAD_SUCCESS:
Bitmap bitmap = (Bitmap) msg.obj;
setImageBitmap(bitmap);
break;
case LOAD_ERROR:
int resid = (Integer) msg.obj;
setImageResource(resid);
break;
}
};
};
public SmartImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public SmartImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public SmartImageView(Context context) {
super(context);
}
/**
* 设置一个要加载的图片的url路径
* @param url
*/
public void setImageUrl(final String url){
new Thread(){
public void run() {
Bitmap bitmap = ImageUtils.getUrlBitmap(url);
if(bitmap!=null){
//获取图片成功了.
Message msg = new Message();
msg.obj = bitmap;
msg.what = LOAD_SUCCESS;
handler.sendMessage(msg);
}
};
}.start();
}
/**
* 设置一个要加载的图片的url路径
* @param url
*/
public void setImageUrl(final String url,final int fallbackres){
new Thread(){
public void run() {
Bitmap bitmap = ImageUtils.getUrlBitmap(url);
if(bitmap!=null){
//获取图片成功了.
Message msg = new Message();
msg.obj = bitmap;
msg.what = LOAD_SUCCESS;
handler.sendMessage(msg);
}else{
Message msg = new Message();
msg.obj = fallbackres;
msg.what = LOAD_ERROR;
handler.sendMessage(msg);
}
};
}.start();
}
}