需要配置联网权限
需要配置两个xml页面
//列表 <ListView android:scrollbars="none" android:overScrollMode="never" android:overScrollFooter="@android:color/white" android:overScrollHeader="@android:color/black" android:divider="@null" android:id="@+id/listview" android:layout_width="match_parent" android:layout_height="wrap_content"> </ListView>
private static final String TAG ="json"; private List<Map<String, Object>> lists; private SimpleAdapter adapter; private ListView listView; new Thread() { @Override public void run() { //创建okhtto请求的对象 OkHttpClient okHttpClient = new OkHttpClient(); //创建请求连接,url里面存放请求连接,get表示其实get请求 Request request = new Request.Builder().url("https://www.nhl520.cn/json.php").get().build(); try { Response response = okHttpClient.newCall(request).execute(); //定义字符串接收请求信息 String string2 = response.body().string(); System.out.println("String:" + string2); JSONObject jsonObjectALL = new JSONObject(string2); // 通过标识(person),获取JSON数组 JSONArray jsonArray = jsonObjectALL.getJSONArray("person"); // Log.e("提交失败", jsonArray+""); lists = new ArrayList<>(); for (int i = 0; i < jsonArray.length(); i++) { // JSON数组里面的具体-JSON对象 JSONObject jsonObject = jsonArray.getJSONObject(i); String name = jsonObject.optString("name", null); String time = jsonObject.optString("time", null); String content = jsonObject.optString("content", null); String imgtx = jsonObject.optString("tx", null); String imgurl = jsonObject.optString("url", null); //System.out.println(age); Map<String, Object> map = new HashMap<>(); map.put("name", name); map.put("time", time); map.put("content", content); map.put("tx", imgtx); map.put("urlimg", imgurl); lists.add(map); // lists2.add(imgurl); } //适配器指定应用自己定义的xml格式 adapter = new SimpleAdapter(getActivity(), lists, R.layout.item, new String[]{"name", "time", "content","tx","urlimg"}, new int[]{R.id.text1, R.id.text2, R.id.text3,R.id.itemtx,R.id.image1}); listView = view.findViewById(R.id.listview); //利用glide在列表加载图片开始 adapter.setViewBinder(new SimpleAdapter.ViewBinder() { @Override public boolean setViewValue(View view, Object data, String textRepresentation) { if (view instanceof ImageView){ ImageView iv= (ImageView)view; GlideUtil.GlideWithPlaceHolder(getActivity(), data.toString()) .placeholder(R.mipmap.itemtrue)//加载过程中图片展示 .error(R.mipmap.itemflase)//加载失败图片展示 .into(iv); return true; }else return false; } }); //利用glide在列表加载图片结束 //要想与主UI交互需要使用runOnUiThread这个方法实现Runnable的抽象类,进行交互 getActivity().runOnUiThread(new Runnable() { @Override public void run() { listView.setAdapter(adapter); } }); } catch (Exception e) { e.printStackTrace(); } } } .start();
再配置Java类
public class GlideUtil { public static RequestBuilder<Drawable> GlideWithPlaceHolder(Context context, Object object) { return Glide.with(context).load(object).apply(new RequestOptions().placeholder(R.mipmap.home).dontAnimate()); //加载图片 } }