import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
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.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

/**
* Created by lenovo on 2017/12/1.
*/

public class MyAdapter extends BaseAdapter {
private List<Result.NewslistBean>data;
private Context context;

public MyAdapter(List<Result.NewslistBean> data, Context context) {
this.data = data;
this.context = context;
}

@Override
public int getCount() {
return data.size();
}

@Override
public Object getItem(int i) {
return data.get(i);
}

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

@Override
public View getView(int i, View view, ViewGroup viewGroup) {
ViewHolder viewHolder;
if (view == null) {
view = LayoutInflater.from(context).inflate(R.layout.item, null);
viewHolder = new ViewHolder();
viewHolder.title= view.findViewById(R.id.text1);
viewHolder.text= view.findViewById(R.id.description);
viewHolder.img= view.findViewById(R.id.image);
view.setTag(viewHolder);//绑定ViewHolder对象
}
else {
viewHolder = (ViewHolder)view.getTag();//取出ViewHolder对象
}

viewHolder.text.setText(data.get(i).getTitle());
viewHolder.title.setText(data.get(i).getCtime());
new MyTask(viewHolder.img).execute(data.get(i).getPicUrl());
return view;
}


/*存放控件*/
class ViewHolder {
public TextView title;
public TextView text;
public ImageView img;
}
class MyTask extends AsyncTask<String,Void,Bitmap> {
private ImageView img;

public MyTask(ImageView img) {
this.img = img;
}

//运行在后台,进行网络请求,子线程
@Override
protected Bitmap doInBackground(String... strings) {//...可变长类型 string....相当于 String[]

Bitmap bitmap=null;

try {
//1.创建URL
URL url=new URL(strings[0]);
//2.打开连接
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

//3.设置
urlConnection.setRequestMethod("GET");
urlConnection.setReadTimeout(5000);
urlConnection.setConnectTimeout(5000);
//4.判断响应码
if(urlConnection.getResponseCode()==200){
//5.获取数据
InputStream inputStream = urlConnection.getInputStream();

bitmap = BitmapFactory.decodeStream(inputStream);


}


} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}


return bitmap;
}

//在进行网络请求得到数据之后,要操作的事件,,解析,更新ui
@Override
protected void onPostExecute(Bitmap s) {
img.setImageBitmap(s);





}
}
}