listView图文显示! 并且简单解决一下图片混乱问题
Posted 粪乧
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了listView图文显示! 并且简单解决一下图片混乱问题相关的知识,希望对你有一定的参考价值。
现在很多使用的应用中,都有一些图文兼并的消息展示,并且是列表形式实现的! 其中不乏有一些是使用的Listview来展示出来的. 今天简单的写了个demo再来回顾一下基础知识.
先来看看效果
现在来说说代码
这里我使用的是官方提供的Volley网络框架
在build中添加这个
dependencies
compile 'eu.the4thfloor.volley:com.android.volley:2015.05.28'
MainActivity.java
package com.xyb.newslistview;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ListView;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity
private ListView listView; // 定义出listview
private RequestQueue requestQueue; // 定义一个请求队列 使用volley包下的 官方产品棒棒哒!
private String HTTPURL = "http://litchiapi.jstv.com/api/" +
"GetFeeds?column=3&PageSize=20&pageIndex=1&val=100511D3BE5301280E0992C73A9DEC41";//请求的网址
private ArrayList<NewsEntity.ParamzEntity.FeedsEntity.DataEntity> dataEntities
= new ArrayList<>();// 坑爹的GsonFormat生成的 但是还真好用!
private ListViewAdapter listViewAdapter; // listview必备是配置是也!
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
requestQueue = Volley.newRequestQueue(this);
initView();// 写个方法来初始化控件
initData();// 写个方法来设置数据
private void initData()
/**
* 第一个是请求的网址
* 第二个为请求成功的监听实现方法参数为解析到的String类型数据
* 第三个是请求失败监听,那就把你失败后要执行的方法写在这里
* **/
StringRequest stringRequest = new StringRequest(HTTPURL, new Response.Listener<String>()
@Override
public void onResponse(String response)
try
// 原生的抠脚json解析,回顾回顾.....
JSONObject jsonObject = new JSONObject(response);
JSONObject object = jsonObject.getJSONObject("paramz");
JSONArray jsonArray = object.getJSONArray("feeds");
NewsEntity.ParamzEntity.FeedsEntity.DataEntity dataEntity;
for (int i = 0; i < jsonArray.length(); i++)
// 将集合遍历额
JSONObject json = jsonArray.getJSONObject(i).getJSONObject("data");
String subject = json.getString("subject");
String summary = json.getString("summary");
String cover = "http://litchiapi.jstv.com" + json.getString("cover");
dataEntity = new NewsEntity.ParamzEntity.FeedsEntity.DataEntity(subject, summary, cover);
dataEntities.add(dataEntity);
listViewAdapter.addNews(dataEntities);// 适配器中数据设置的方法将数据传递过去 notify一下
catch (JSONException e)
e.printStackTrace();
, new Response.ErrorListener()
@Override
public void onErrorResponse(VolleyError error)
);
requestQueue.add(stringRequest); // 请求需要加到队列中才能执行哦 这个是先执行哦 别看写在下面 哈哈
/**
* 初始化控件的方法
**/
private void initView()
listViewAdapter = new ListViewAdapter(this);
listView = (ListView) findViewById(R.id.list);
listView.setAdapter(listViewAdapter);
NewsEntity.java
package com.xyb.newslistview;
/*
_ooOoo_
o8888888o
88" . "88
(| -_- |)
O\\ = /O
____/`---'\\____
.' \\\\| |// `.
/ \\\\||| : |||// \\
/ _||||| -:- |||||- \\
| | \\\\\\ - /// | |
| \\_| ''\\---/'' | |
\\ .-\\__ `-` ___/-. /
___`. .' /--.--\\ `. . __
."" '< `.___\\_<|>_/___.' >'"".
| | : `- \\`.;`\\ _ /`;.`/ - ` : | |
\\ \\ `-. \\_ __\\ /__ _/ .-` / /
======`-.____`-.___\\_____/___.-`____.-'======
`=---='
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
佛祖保佑 永无BUG
*/
import java.util.List;
/***
* BY YanBinXie AT 15/11/10 下午3:08
*/
public class NewsEntity
private String status;
private ParamzEntity paramz;
public void setStatus(String status)
this.status = status;
public void setParamz(ParamzEntity paramz)
this.paramz = paramz;
public String getStatus()
return status;
public ParamzEntity getParamz()
return paramz;
public static class ParamzEntity
private int PageIndex;
private int PageSize;
private int TotalCount;
private int TotalPage;
/**
* id : 299058
* oid : 288328
* category : article
* data : "subject":"工作人员套取新农合565元被降级","summary":"昨天记者获悉,驻马店市纪委通报4起涉医领域违纪违法典型案件。","cover":"/Attachs/Article/288328/65b28e724f3b4a65ae7bb3f5c97699ab_padmini.JPG","pic":"","format":"txt","changed":"2015-09-19 19:35:53"
*/
private List<FeedsEntity> feeds;
public void setPageIndex(int PageIndex)
this.PageIndex = PageIndex;
public void setPageSize(int PageSize)
this.PageSize = PageSize;
public void setTotalCount(int TotalCount)
this.TotalCount = TotalCount;
public void setTotalPage(int TotalPage)
this.TotalPage = TotalPage;
public void setFeeds(List<FeedsEntity> feeds)
this.feeds = feeds;
public int getPageIndex()
return PageIndex;
public int getPageSize()
return PageSize;
public int getTotalCount()
return TotalCount;
public int getTotalPage()
return TotalPage;
public List<FeedsEntity> getFeeds()
return feeds;
public static class FeedsEntity
private int id;
private int oid;
private String category;
/**
* subject : 工作人员套取新农合565元被降级
* summary : 昨天记者获悉,驻马店市纪委通报4起涉医领域违纪违法典型案件。
* cover : /Attachs/Article/288328/65b28e724f3b4a65ae7bb3f5c97699ab_padmini.JPG
* pic :
* format : txt
* changed : 2015-09-19 19:35:53
*/
private DataEntity data;
public void setId(int id)
this.id = id;
public void setOid(int oid)
this.oid = oid;
public void setCategory(String category)
this.category = category;
public void setData(DataEntity data)
this.data = data;
public int getId()
return id;
public int getOid()
return oid;
public String getCategory()
return category;
public DataEntity getData()
return data;
public static class DataEntity
private String subject;
private String summary;
private String cover;
private String pic;
private String format;
private String changed;
public DataEntity(String subject, String summary, String cover)
this.subject = subject;
this.summary = summary;
this.cover = cover;
public void setSubject(String subject)
this.subject = subject;
public void setSummary(String summary)
this.summary = summary;
public void setCover(String cover)
this.cover = cover;
public void setPic(String pic)
this.pic = pic;
public void setFormat(String format)
this.format = format;
public void setChanged(String changed)
this.changed = changed;
public String getSubject()
return subject;
public String getSummary()
return summary;
public String getCover()
return cover;
public String getPic()
return pic;
public String getFormat()
return format;
public String getChanged()
return changed;
ListViewAdapter.java
package com.xyb.newslistview;
/*
_ooOoo_
o8888888o
88" . "88
(| -_- |)
O\\ = /O
____/`---'\\____
.' \\\\| |// `.
/ \\\\||| : |||// \\
/ _||||| -:- |||||- \\
| | \\\\\\ - /// | |
| \\_| ''\\---/'' | |
\\ .-\\__ `-` ___/-. /
___`. .' /--.--\\ `. . __
."" '< `.___\\_<|>_/___.' >'"".
| | : `- \\`.;`\\ _ /`;.`/ - ` : | |
\\ \\ `-. \\_ __\\ /__ _/ .-` / /
======`-.____`-.___\\_____/___.-`____.-'======
`=---='
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
佛祖保佑 永无BUG
*/
import android.content.Context;
import android.graphics.Bitmap;
import android.support.v4.util.LruCache;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import com.android.volley.toolbox.Volley;
import java.util.ArrayList;
/***
* BY YanBinXie AT 15/11/10 下午3:06
*/
public class ListViewAdapter extends BaseAdapter
private Context context;
private ArrayList<NewsEntity.ParamzEntity.FeedsEntity.DataEntity> newsEntities;
private NetworkImageView iv;
private ImageLoader imageLoader;
public ListViewAdapter(Context context)
this.context = context;
RequestQueue queue = Volley.newRequestQueue(context);
imageLoader = new ImageLoader(queue, new ImageLoader.ImageCache()
int maxMemory = (int) Runtime.getRuntime().maxMemory();
int cacheSize = maxMemory / 8; // imageLoader 最大缓存哦哦
private LruCache<String, Bitmap> mCache = new LruCache<>(cacheSize);
@Override
public Bitmap getBitmap(String url)
return mCache.get(url);
@Override
public void putBitmap(String url, Bitmap bitmap)
mCache.put(url, bitmap);
);
public void addNews(ArrayList<NewsEntity.ParamzEntity.FeedsEntity.DataEntity> newsEntities)
this.newsEntities = newsEntities;
notifyDataSetChanged();
@Override
public int getCount()
return newsEntities != null && newsEntities.size() > 0 ? newsEntities.size() : 0;
@Override
public Object getItem(int position)
return newsEntities != null && newsEntities.size() > 0 ? newsEntities.get(position) : null;
@Override
public long getItemId(int position)
return newsEntities != null && newsEntities.size() > 0 ? position : 0;
@Override
public View getView(int position, View convertView, ViewGroup parent)
View view;
/**
* 这是一种实现方法 但是我感觉使用ViewHolder的方法比较好,这里偷懒了,,
* */
TextView title,summary;
if (convertView == null)
view = LayoutInflater.from(context).inflate(R.layout.list_item, null);
else
view = convertView;
iv = (NetworkImageView) view.findViewById(R.id.iv);
summary = (TextView) view.findViewById(R.id.summary);
title = (TextView) view.findViewById(R.id.title);
summary.setText(newsEntities.get(position).getSummary());
title.setText(newsEntities.get(position).getSubject());
iv.setDefaultImageResId(R.mipmap.ic_launcher);
iv.setErrorImageResId(R.mipmap.ic_launcher);
iv.setImageUrl(newsEntities.get(position).getCover(), imageLoader);
return view;
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="新闻listview" />
<ListView
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@+id/text" />
</RelativeLayout>
list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="100dp">
<com.android.volley.toolbox.NetworkImageView
android:id="@+id/iv"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_centerVertical="true"
android:padding="5dp"/>
<TextView
android:id="@+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_toRightOf="@id/iv"
android:gravity="center_vertical"
android:textSize="14sp"
android:textStyle="bold" />
<TextView
android:id="@+id/summary"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/title"
android:layout_marginTop="8dp"
android:layout_toRightOf="@id/iv"
android:textSize="12sp" />
</RelativeLayout>
代码就这些 大牛勿喷. 同时大家可以使用一些简单易用的图片加载方法,但是要解决图片混乱好象有点繁琐,以后继续学学! UIL,Picasso,Fresco,Glide 等等很多 图片加载库.
还有可能大家学的抠脚json解析有点坑爹效率低,那么我推荐大家使用Gson, fastjson(据说是最快的).下面我简单记录一下使用方法.
Gson :
在build中添加这个
dependencies
compile 'com.google.code.gson:gson:2.2.4'
代码中
这个为实体类的最外层类名 与类对象 可以一层一层的扒扒!
Gson gson = new Gson();
NewsEntity newsEntity = gson.fromJson(response, NewsEntity.class);
只需要这两行就完事了
FastJson :
添加
compile 'com.alibaba:fastjson:1.2.7'
代码使用 说明同上!
NewsEntity newsEntity = JSON.parseObject(response,NewsEntity.class);
就这一行 是不是感觉好方便..哈哈 但是限制挺多的 json数据必须规范才行哦 !哈哈
互相交流 大牛勿喷!
代码下载地址! 点我啊
以上是关于listView图文显示! 并且简单解决一下图片混乱问题的主要内容,如果未能解决你的问题,请参考以下文章