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();
}
}
Android核心基础(五)的更多相关文章
- Android核心基础(手机卫士的一个知识点总结)
注意:有些功能是需要权限的,在这里并没有写出来,在程序运行中,根据程序报的错误,添加相应的权限即可,里面的具体里面可能有一些小细节,没有明确的写出来,具体的需要在程序中自己调试,解决. 这个总结涵盖了 ...
- Android核心基础(四)
1.联系人表结构 添加一条联系人信息 package com.itheima.insertcontact; import android.app.Activity; import android.co ...
- Android核心基础(二)
1.对应用进行单元测试 在实际开发中,开发android软件的过程需要不断地进行测试.而使用Junit测试框架,侧是正规Android开发的必用技术,在Junit中可以得到组件,可以模拟发送事件和检测 ...
- Android核心基础(十)
1.音频采集 你可以使用手机进行现场录音,实现步骤如下: 第一步:在功能清单文件AndroidManifest.xml中添加音频刻录权限: <uses-permission android:na ...
- Android核心基础
第三代移动通讯技术(3rd Generation) ,支持高速数据传输的蜂窝移动通讯技术.3G与2G的主要区别是传输数据的速度. 1987年,第一台模拟制式手机(1G)问世,只能进行语音通话,型号:摩 ...
- Android核心基础(十一)
1.Android的状态栏通知(Notification) 通知用于在状态栏显示消息,消息到来时以图标方式表示,如下: //获取通知管理器 NotificationManager mNotificat ...
- Android应用的核心基础
Android4开发入门经典 之 第二部分:Android应用的核心基础 Android应用中的组件 Application Components Android应用中最主要的组件是: 1:Activ ...
- 20155228 实验五 Android开发基础
20155228 实验五 Android开发基础 实验内容 1.掌握Socket程序的编写: 2.掌握密码技术的使用: 3.设计安全传输系统. 实验要求 1.没有Linux基础的同学建议先学习< ...
- Android零基础入门第1节:Android的前世今生
原文:Android零基础入门第1节:Android的前世今生 现在网上有很多各色Android资料了,但相对来说还是比较零散,Android覆盖的范围极广,最近刚好有机会全部拉通整理一遍,也保存起来 ...
随机推荐
- android面试题集1
Android 面试题(有详细答案) 附带答案,共100分 一.选择题(30题,每题1.5分,共45分) 1.java.io包中定义了多个流类型来实现输入和输出功能,可以从不同的角度对其进行分类,按功 ...
- CSS学习笔记——盒模型,块级元素和行内元素的区别和特性
今天本来打算根据自己的计划进行前端自动化的学习的,无奈早上接到一个任务需求需要新增一个页面.自从因为工作需要转前端之后,自己的主要注意力几 乎都放在JavaScript上面了,对CSS和HTML这方面 ...
- Android之日期及时间选择对话框
转:http://www.cnblogs.com/linjiqin/archive/2011/03/10/1980215.html main.xml布局文件 <?xml version=&quo ...
- GoEasy实现web实时推送过程中的自动补发功能
熟悉GoEasy推送的朋友都知道GoEasy推送实现web实时推送并且能够非常准确稳定地将信息推送到客户端.在后台功能中查看接收信息详情时,可有谁注意到有时候在发送记录里有一个红色的R标志?R又代表的 ...
- [Math]Divide Two Integers
otal Accepted: 54356 Total Submissions: 357733 Difficulty: Medium Divide two integers without using ...
- [Effective Modern C++] Item 4. Know how to view deduced types - 知道如何看待推断出的类型
条款四 知道如何看待推断出的类型 基础知识 有三种方式可以知道类型推断的结果: IDE编辑器 编译器诊断 运行时输出 使用typeid()以及std::type_info::name可以获取变量的类型 ...
- [转]activiti5用户任务分配
用户任务分配办理人:1.用户任务可以直接分配给一个用户,这可以通过humanPerformer元素定义. humanPerformer定义需要一个 resourceAssignmentExpressi ...
- Uncaught TypeError: Object [object Object] has no method 'live'
$( selector ).live( events, data, handler ); // jQuery 1.3+$( document ).delegate( se ...
- AngularJS的指令(Directive) compile和link的区别及使用示例
如果我想实现这样一个功能,当一个input失去光标焦点时(blur),执行一些语句,比如当输入用户名后,向后台发ajax请求查询用户名是否已经存在,好有及时的页面相应. 输入 camnpr 失去焦点后 ...
- 显示Title和隐藏Title的ListView
一.主要步骤 ①.调用ListView的addHeaderView(),创建一个与Title一样高的View,这样ListView就不会刚开始被遮盖了 ②.调用ListView的setOnTouchE ...