xml文件
main布局
<com.handmark.pulltorefresh.library.PullToRefreshListView
android:id="@+id/pull_refresh_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
></com.handmark.pulltorefresh.library.PullToRefreshListView>
MainActivity类
public class MainActivity extends AppCompatActivity {
private ListView lv;
private List<Jbean.NewslistBean> newslist;
private Shipei sheipei;
private PullToRefreshListView pi;
private Handler handler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pi = (PullToRefreshListView) findViewById(R.id.pull_refresh_list);
shuju();
}
public void shuju(){
new Thread(){
@Override
public void run() {
super.run();
final String getjson = Qingqiu.getjson();
runOnUiThread(new Runnable() {
@Override
public void run() {
Gson gson = new Gson();
Jbean jBean = gson.fromJson(getjson, Jbean.class);
newslist = jBean.newslist;
sheipei = new Shipei();
pi.setAdapter(sheipei);
pi.onRefreshComplete();//设置让刷新关闭
}
});
}
}.start();
}
class Shipei extends BaseAdapter {
@Override
public int getCount() {
return newslist.size();
}
@Override
public Object getItem(int i) {
return newslist.get(i);
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
ViewHolder hd = null;
//优化
if (view==null){
hd = new ViewHolder();
view = View.inflate(MainActivity.this,R.layout.item,null);
hd.iv = view.findViewById(R.id.iv);
hd.tv1 = view.findViewById(R.id.tv1);
hd.tv2 = view.findViewById(R.id.tv2);
view.setTag(hd);
}else {
hd = (ViewHolder) view.getTag();
}
hd.tv1.setText(newslist.get(i).title);
hd.tv2.setText(newslist.get(i).ctime);
ImageLoader.getInstance().displayImage(newslist.get(i).picUrl,hd.iv);
return view;
}
}
class ViewHolder{
ImageView iv;
TextView tv1,tv2;
}
}
Img类
ImageLoaderConfiguration configuration = new ImageLoaderConfiguration.Builder(this).build(); ImageLoader.getInstance().init(configuration);
Qingqiu类
public class Qingqiu { static String path = "https://api.tianapi.com/wxnew/?key=8d6e3228d25298f13af4fc40ce6c9679&num=10&page=1"; private static ByteArrayOutputStream outputStream; public static String getjson(){ try { URL url = new URL(path); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setReadTimeout(5000); int responseCode = connection.getResponseCode(); outputStream = new ByteArrayOutputStream(); if (responseCode==200){ InputStream inputStream = connection.getInputStream(); byte[] b = new byte[1024]; int len = -1; while ((len=inputStream.read(b)) != -1){ outputStream.write(b,0,len); } return outputStream.toString(); } } catch (Exception e) { e.printStackTrace(); } return outputStream.toString(); } }