//主界面布局
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:id="@+id/buthttp"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
android:text="http"
android:onClick="getHttpData"
app:layout_constraintRight_toRightOf="parent"/>
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:id="@+id/butclient"
app:layout_constraintTop_toBottomOf="@id/buthttp"
app:layout_constraintLeft_toLeftOf="parent"
android:text="client"
app:layout_constraintRight_toRightOf="parent"/>
<ListView
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintTop_toBottomOf="@id/butclient"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
android:id="@+id/listview"
></ListView>
</android.support.constraint.ConstraintLayout>
//子条目布局
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">
<TextView
android:layout_width="0dp"
android:layout_height="100dp"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintRight_toLeftOf="@id/imageview"
app:layout_constraintLeft_toLeftOf="parent"
android:id="@+id/textview1"
/>
<TextView
android:layout_width="0dp"
android:layout_height="100dp"
app:layout_constraintTop_toBottomOf="@id/textview1"
app:layout_constraintRight_toLeftOf="@id/imageview"
app:layout_constraintLeft_toLeftOf="parent"
android:id="@+id/textview2"
/>
<ImageView
android:layout_width="150dp"
android:layout_height="200dp"
app:layout_constraintRight_toRightOf="parent"
android:id="@+id/imageview"
/>
</android.support.constraint.ConstraintLayout>
//主函数MainActivity
package com.example.rikao1106;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private Button buttonhttp,buttonclient;
private ListView listView;
private String path = "http://api.expoon.com/AppNews/getNewsList/type/1/p/1";
private MyBaseAdafter adafter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = findViewById(R.id.listview);
adafter = new MyBaseAdafter(MainActivity.this);
listView.setAdapter(adafter);
findViewById(R.id.buthttp).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Utils.getRequest2(path, Bean.class, new Utils.BeanResultCallback2<Bean>() {
@Override
public void onSuccess(Bean object) {
adafter.setListData(object.getData());
}
});
/*new AsyncTask<String,Void,List<Bean.DataBean>>(){
@Override
protected List<Bean.DataBean> doInBackground(String... strings) {
List<Bean.DataBean> dataBeans = Utils.httpMode(strings[0]);
return dataBeans;
}
@Override
protected void onPostExecute(List<Bean.DataBean> dataBeans) {
adafter.setListData(dataBeans);
}
}.execute(path);*/
}
});
}
private void requestData() {
Utils.getRequest2("", Bean.class, new Utils.BeanResultCallback() {
@Override
public void onSuccess(Object object) {
Bean bean = (Bean) object;
}
});
}
/*private void getHttpData(View v){
new AsyncTask<String,Void,List<Bean.DataBean>>(){
@Override
protected List<Bean.DataBean> doInBackground(String... strings) {
List<Bean.DataBean> dataBeans = Utils.httpMode(strings[0]);
return dataBeans;
}
@Override
protected void onPostExecute(List<Bean.DataBean> dataBeans) {
adafter.setListData(dataBeans);
}
}.execute(path);
}*/
}
//新建一个bean类
package com.example.rikao1106;
import java.util.List;
public class Bean {
private List<DataBean> data;
public List<DataBean> getData() {
return data;
}
public void setData(List<DataBean> data) {
this.data = data;
}
public static class DataBean {
private String news_title;
private String news_summary;
private String pic_url;
public String getNews_title() {
return news_title;
}
public void setNews_title(String news_title) {
this.news_title = news_title;
}
public String getNews_summary() {
return news_summary;
}
public void setNews_summary(String news_summary) {
this.news_summary = news_summary;
}
public String getPic_url() {
return pic_url;
}
public void setPic_url(String pic_url) {
this.pic_url = pic_url;
}
}
}
//创建适配器
package com.example.rikao1106;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class MyBaseAdafter extends BaseAdapter {
private Context context;
private List<Bean.DataBean>mlist;
public MyBaseAdafter(Context context) {
this.context = context;
mlist = new ArrayList<>();
}
public void setListData(List<Bean.DataBean> list){
this.mlist = list;
notifyDataSetChanged();
}
@Override
public int getCount() {
return mlist.size();
}
@Override
public Bean.DataBean getItem(int position) {
return mlist.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHoder viewHoder;
if(convertView==null){
convertView = LayoutInflater.from(context).inflate(R.layout.item,parent,false);
viewHoder = new ViewHoder();
viewHoder.textView1 = convertView.findViewById(R.id.textview1);
viewHoder.textView2 = convertView.findViewById(R.id.textview2);
viewHoder.imageView = convertView.findViewById(R.id.imageview);
convertView.setTag(viewHoder);
}else{
viewHoder = (ViewHoder) convertView.getTag();
}
viewHoder.textView1.setText(mlist.get(position).getNews_title());
viewHoder.textView2.setText(mlist.get(position).getNews_summary());
//RxJava
//加载图片
/*new AsyncTask<String,Void,Bitmap>(){
@Override
protected Bitmap doInBackground(String... strings) {
Bitmap bitmp = Utils.getBitmp(strings[0]);
return bitmp;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
viewHoder.imageView.setImageBitmap(bitmap);
}
}.execute(mlist.get(position).getPic_url());*/
//外面调用简单了
//还有一个错乱问题
//Utils.getBitmap(getItem(position).getPic_url(), viewHoder.imageView);
/*
假设imageView(0)第一次进来加载1.jpg图片
往上滑动,imageView(0)滑出去
底下一个view进来
复用imageView(0)加载1.jpg图片没有完成
给imageView(0)加载4.jpg图片
imageView(0)有两个任务
imageView(0)可能显示1.jpg也可能显示4.jpg.发生错乱
*/
/*
每次加载图片时url和imageView绑定
*/
//第一次绑定1.jpg
//第二次从新绑定到4.jpg
//后用的把先用的顶掉
//加载前绑定:外部做的
viewHoder.imageView.setTag(getItem(position).getPic_url());
//viewHoder.imageView.setTag(0, "");
//Utils内部不只到绑定细节.没办法直接加载图片给ImageView
//外部来做,显示图片:需要关注什么(Bitmap, 当前bitmap图片的url路径)
Utils.getBitmap(getItem(position).getPic_url(), new Utils.Callback() {
//按照合同实现
@Override
public void loadImageSuccess(String imageUrl, Bitmap bitmap) {
if(imageUrl.equals(viewHoder.imageView.getTag())) {
viewHoder.imageView.setImageBitmap(bitmap);
} else {
Log.i("TEST", "错乱: " );
}
}
});
return convertView;
}
class ViewHoder{
private TextView textView1,textView2;
private ImageView imageView;
}
}
//工具类
package com.example.rikao1106;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.telecom.Call;
import android.widget.ImageView;
import com.google.gson.Gson;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
public class Utils {
//获取网络连接
public static List<Bean.DataBean> httpMode (String path){
try {
HttpURLConnection urlConnection = (HttpURLConnection) new URL(path).openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setReadTimeout(5000);
urlConnection.setConnectTimeout(5000);
if(urlConnection.getResponseCode()==200){
//调用转换字符串方法
String string = getString(urlConnection.getInputStream());
Bean bean = new Gson().fromJson(string, Bean.class);
List<Bean.DataBean> data = bean.getData();
return data;
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/* public static List<Bean.DataBean> clientMode (String s){
//请求配置
RequestConfig custom = RequestConfig
.custom()
.setConnectTimeout(5000)
.build();
//创建HttpClient
CloseableHttpClient custom1 = HttpClients
.custom()
.setDefaultRequestConfig(custom)
.build();
//创建请求对象
HttpUriRequest request = (HttpUriRequest) RequestBuilder
.get()
.setUri(strings[0])
.build();
//执行一个请求
try {
HttpResponse response = custom1.execute(request);
int statusCode = response.getStatusLine().getStatusCode();
if(statusCode == 200){
String json = EntityUtils.toString(response.getEntity());
//得到gson
Bean bean = new Gson().fromJson(json, Bean.class);
List<Bean.DataBean> data = bean.getData();
return data;
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}*/
public static void getBitmap(final String imageUrl, final Callback callback) {
new AsyncTask<String, Void, Bitmap>(){
@Override
protected Bitmap doInBackground(String... strings) {
return getBitmp(strings[0]);
}
@Override
protected void onPostExecute(Bitmap bitmap) {
//按照合同执行
callback.loadImageSuccess(imageUrl, bitmap);
}
}.execute(imageUrl);
}
//把线程吞掉
//因为是异步操作,不知道什么时候返回bitmap.所以不能直接返回结果
//加载图片大部分情况下是为了展示
public static void getBitmap(String imgUrl, final ImageView imageView) {
/
new AsyncTask<String,Void,Bitmap>(){
@Override
protected Bitmap doInBackground(String... strings) {
return Utils.getBitmp(strings[0]);
}
@Override
protected void onPostExecute(Bitmap bitmap) {
imageView.setImageBitmap(bitmap);
}
}.execute(imgUrl);
}
/**
* 接口 相当于合同
*/
public interface Callback {
public void loadImageSuccess(String imageUrl, Bitmap bitmap);
}
//网络请求一张图片
public static Bitmap getBitmp (String path){
try {
HttpURLConnection urlConnection = (HttpURLConnection) new URL(path).openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setReadTimeout(5000);
urlConnection.setConnectTimeout(5000);
if(urlConnection.getResponseCode()==200){
//调用转换字符串方法
Bitmap bitmap = BitmapFactory.decodeStream(urlConnection.getInputStream());
return bitmap;
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public interface BeanResultCallback2<T> {
void onSuccess(T object);
}
public static void getRequest2(String url, final Class clazz, final BeanResultCallback2 callback) {
new AsyncTask<String, Void, Object>(){
@Override
protected Object doInBackground(String... strings) {
return getRequest(strings[0], clazz);
}
@Override
protected void onPostExecute(Object o) {
callback.onSuccess(o);
}
}.execute(url);
}
public interface BeanResultCallback {
void onSuccess(Object object);
}
public static void getRequest2(String url, final Class clazz, final BeanResultCallback callback) {
new AsyncTask<String, Void, Object>(){
@Override
protected Object doInBackground(String... strings) {
return getRequest(strings[0], clazz);
}
@Override
protected void onPostExecute(Object o) {
callback.onSuccess(o);
}
}.execute(url);
}
//执行一个get请求,返回bean
public static <T> T getRequest(String url, Class clazz) {
String result = getRequest(url);
T t = (T) new Gson().fromJson(result, clazz);
return t;
}
//执行一个get请求,返回String结果
public static String getRequest(String url) {
String result = "";
try {
HttpURLConnection urlConnection = (HttpURLConnection) new URL(url).openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setReadTimeout(5000);
urlConnection.setConnectTimeout(5000);
if(urlConnection.getResponseCode()==200){
//调用转换字符串方法
result = getString(urlConnection.getInputStream());
}
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
public static String getString(InputStream is) throws IOException {
StringBuilder builder = new StringBuilder();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
for (String i = bufferedReader.readLine();i != null;i=bufferedReader.readLine()){
builder.append(i);
}
return builder.toString();
}
}