1.难点
ListView中两个Item的切换onProgressUpdate: 需要在 doInBackg
主要逻辑代码
MyAdapter
package com.example.myadapter;
import java.util.List;
import android.R.integer;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.example.chatutils.ChatMessage;
import com.example.chatutils.ChatMessage.type;
import com.example.mylistviewdemo2.R;
public class MyAdapter extends BaseAdapter {
private Context context;
private List<ChatMessage> list;
public MyAdapter(Context context, List<ChatMessage> list) {
super();
this.context = context;
this.list = list;
}
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int position) {
return list.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder vh;
if (getItemViewType(position) == 0) {// 我发消息
if(convertView == null){
vh = new ViewHolder();
convertView = LayoutInflater.from(context).inflate(R.layout.activity_item_right, null);
vh.tv_time = (TextView) convertView.findViewById(R.id.tv_time2);
vh.tv_message = (TextView) convertView.findViewById(R.id.message2);
convertView.setTag(vh);
}else{
vh = (ViewHolder) convertView.getTag();
}
vh.tv_time.setText(list.get(position).getTime());
vh.tv_message.setText(list.get(position).getMessage());
}
if (getItemViewType(position) == 1) {// 我收消息
if(convertView == null){
vh = new ViewHolder();
convertView = LayoutInflater.from(context).inflate(R.layout.activity_item_left, null);
vh.tv_time = (TextView) convertView.findViewById(R.id.tv_time1);
vh.tv_message = (TextView) convertView.findViewById(R.id.message1);
}else{
vh = (ViewHolder) convertView.getTag();
}
vh.tv_time.setText(list.get(position).getTime());
vh.tv_message.setText(list.get(position).getMessage());
}
return convertView;
}
class ViewHolder{
TextView tv_time;
TextView tv_message;
}
@Override
public int getViewTypeCount() {
return 2;
}
@Override
public int getItemViewType(int position) {
if (list.get(position).getType().equals(type.OUTCOMING.toString())) {
return 0;
} else {
return 1;
}
}
}
MainActivity
package com.example.mylistviewdemo2;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.example.chatutils.Chat;
import com.example.chatutils.ChatMessage;
import com.example.chatutils.ChatMessage.type;
import com.example.myadapter.MyAdapter;
import com.example.utils.Utrls;
import com.google.gson.Gson;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
public class MainActivity extends Activity {
private ListView listView;
private Button sendButton;
private EditText editText;
private String url = "http://www.tuling123.com/openapi/api?key=5c0cb5d8206e4e328f833ebe56d9aa82&info=";
private List<ChatMessage> list = new ArrayList<ChatMessage>();// 获取得到的数据源
private com.example.myadapter.MyAdapter adapter;
private SimpleDateFormat form = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listview);
sendButton = (Button) findViewById(R.id.send);
editText = (EditText) findViewById(R.id.edit);
sendButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
ChatMessage chat = new ChatMessage();
String message1 = editText.getText().toString();
chat.setMessage(message1);
chat.setName("我");
chat.setTime(form.format(new Date()));
chat.setType(type.OUTCOMING.toString());
list.add(chat);
adapter = new com.example.myadapter.MyAdapter(
MainActivity.this, list);// 发送消息
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();// 提醒数据更新
try {
new MyTask().execute(url
+ URLEncoder.encode(message1, "UTF-8"));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
editText.setText("");
}
});
initData();
}
private void initData() {// 刚进入时显示问候语
ChatMessage chat = new ChatMessage();
chat.setMessage("您好,我是蛋蛋,很高兴为您服务!");
chat.setTime(form.format(new Date()));
chat.setType(type.INCOMING.toString());
list.add(chat);
adapter = new MyAdapter(MainActivity.this, list);
listView.setAdapter(adapter);
}
class MyTask extends AsyncTask<String, Void, List<ChatMessage>> {// 接收消息
@Override
protected List<ChatMessage> doInBackground(String... params) {
// 联网获取json
String json = Utrls.getJsonContent(params[0]);
// 解析json
ChatMessage chat = new ChatMessage();
Chat chat1 = parseGson(json);
chat.setMessage(chat1.getText());
chat.setName("蛋蛋");
chat.setTime(form.format(new Date()));
chat.setType(type.INCOMING.toString());
list.add(chat);
return list;
}
@Override
protected void onPostExecute(List<ChatMessage> result) {
super.onPostExecute(result);
// 在适配器上添加资源
adapter = new com.example.myadapter.MyAdapter(MainActivity.this,
result);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();// 提醒数据更新
}
}
private Chat parseGson(String json) {
Gson gson = new Gson();
Chat chat = gson.fromJson(json, Chat.class);
return chat;
}
}
Utils工具类
package com.example.utils;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
public class Utrls {
public static String getJsonContent(String url) {
String result = "";
HttpURLConnection connection = null;
BufferedReader br = null;
try {
URL url1 = new URL(url);
// 建立一个网络连接
connection = (HttpURLConnection) url1.openConnection();
br = new BufferedReader(new InputStreamReader(
connection.getInputStream(), "UTF-8"));
String line = "";
while ((line = br.readLine()) != null) {
result += line;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close();
connection.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
// 获取图片
public static Bitmap getInage1(String url) {// HttpURLConnection获取
Bitmap bitmap = null;
try {
URL url1 = new URL(url);
// 建立一个网络连接
HttpURLConnection connection = (HttpURLConnection) url1
.openConnection();
// 获取网络返回的数据
BufferedInputStream bis = new BufferedInputStream(
connection.getInputStream());
// 通过decode方法把流转换为图片
bitmap = BitmapFactory.decodeStream(bis);
bis.close();
connection.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
}
数据接口来源:图灵机器人http://www.tuling123.com/openapi/