实现根据图片数量不同的多条目加载
例题:实现根据图片数量不同的多条目加载
在开始之前记得导jsr包(gson)和(universalimageloader)
加权限:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
布局:
<ListView
android:id="@+id/list_view"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
======================================================================
主要代码:(MainActivity)
listView = (ListView) findViewById(R.id.list_view);
//首先判断是否连接网络
boolean result=NetStateUtil.isConn(this);
if(result){
//进行网络请求
MyTask myTask=new MyTask();
myTask.execute("http://v.juhe.cn/toutiao/index?type=top&key=444da40ec8ee43818073d7131c2ffa8f");
}else{
//跳转到设置页面
NetStateUtil.openDg(this);
}
}
class MyTask extends AsyncTask<String,Void,String> {
@Override
protected String doInBackground(String... strings) {
StringBuilder builder=new StringBuilder();
//1.根据url创建URL
try {
URL url=new URL(strings[0]);
//2.打开连接
HttpURLConnection conn =(HttpURLConnection) url.openConnection();
//3.设置
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
//4.判断结果码
if(conn.getResponseCode()==200){
//5.获取数据
InputStream inputStream = conn.getInputStream();
BufferedReader reader=new BufferedReader(new InputStreamReader(inputStream));
String str;
while ((str=reader.readLine())!=null){
builder.append(str);
}
}
} catch (Exception e) {
e.printStackTrace();
}
Log.d("zzz",builder.toString());
return builder.toString();
}
//async 执行完 doinbackground..后 马上来执行onPostExecute方法
@Override
protected void onPostExecute(String s) {
Gson gson=new Gson();
Result result = gson.fromJson(s, Result.class);
//更新listview
MyAdapter adapter=new MyAdapter(MainActivity.this,result.getResult().getData());
listView.setAdapter(adapter);
}
=========================================================
Result解析类
public class Result {
ALT+S(GsonFormat)json解析
}
=============================================================
NetStateUtil类:
class NetStateUtil {
public static boolean isConn(Context context){
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = (NetworkInfo) manager.getActiveNetworkInfo();
if(info!=null && info.isAvailable()){
return true;
}
return false;
}
public static void openDg(final Context context){
AlertDialog.Builder builder=new AlertDialog.Builder(context);
builder.setMessage("是否要进行网络连接设置?");
builder.setPositiveButton("设置", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent intent=null;
//判断手机系统的版本 即API大于10 就是3.0或以上版本
if(android.os.Build.VERSION.SDK_INT>10){
intent = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
}else{
intent = new Intent();
ComponentName component = new ComponentName("com.android.settings","com.android.settings.WirelessSettings");
intent.setComponent(component);
intent.setAction("android.intent.action.VIEW");
}
context.startActivity(intent);
}
});
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
builder.create().show();
}
}
========================================================
MyAdapter适配器类
class MyAdapter extends BaseAdapter{
private Context context;
private List<Result.ResultBean.DataBean> datas;
private DisplayImageOptions options;
public MyAdapter(Context context, List<Result.ResultBean.DataBean> datas) {
this.context = context;
this.datas = datas;
options=new DisplayImageOptions.Builder()
.cacheInMemory(true)//使用内存缓存
.cacheOnDisk(true)//使用磁盘缓存
.showImageOnLoading(R.mipmap.ic_launcher)//设置正在下载的图片
.showImageForEmptyUri(R.mipmap.ic_launcher)//url为空或请求的资源不存在时
.showImageOnFail(R.mipmap.ic_launcher)//下载失败时显示的图片
.bitmapConfig(Bitmap.Config.RGB_565)//设置图片色彩模式
.imageScaleType(ImageScaleType.EXACTLY)//设置图片的缩放模式
.build();
}
//定义三种类型
private final int THREE_IMAGE=0;
private final int TWO_IMAGE=1;
private final int ONE_IMAGE=2;
@Override
public int getCount() {
return datas.size();
}
@Override
public Object getItem(int i) {
return null;
}
@Override
public long getItemId(int i) {
return 0;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
//得到当前条目对应的类型
int type = getItemViewType(i);
if(type==THREE_IMAGE){
ViewHolder3 viewHolder3;
if(view==null){
view=View.inflate(context,R.layout.item_three_image,null);
viewHolder3=new ViewHolder3();
viewHolder3.textView=view.findViewById(R.id.tv_title);
viewHolder3.img1=view.findViewById(R.id.img1);
viewHolder3.img2=view.findViewById(R.id.img2);
viewHolder3.img3=view.findViewById(R.id.img3);
view.setTag(viewHolder3);
}else{
viewHolder3=(ViewHolder3) view.getTag();
}
viewHolder3.textView.setText(datas.get(i).getTitle());
//下载图片
ImageLoader.getInstance().displayImage(datas.get(i).getThumbnail_pic_s(),viewHolder3.img1,options);
ImageLoader.getInstance().displayImage(datas.get(i).getThumbnail_pic_s02(),viewHolder3.img2,options);
ImageLoader.getInstance().displayImage(datas.get(i).getThumbnail_pic_s03(),viewHolder3.img3,options);
return view;
}else if(type==TWO_IMAGE){
ViewHolder2 viewHolder2;
if(view==null){
view=View.inflate(context,R.layout.item_two_image,null);
viewHolder2=new ViewHolder2();
viewHolder2.textView=view.findViewById(R.id.tv_title);
viewHolder2.img1=view.findViewById(R.id.img1);
viewHolder2.img2=view.findViewById(R.id.img2);
view.setTag(viewHolder2);
}else{
viewHolder2=(ViewHolder2) view.getTag();
}
viewHolder2.textView.setText(datas.get(i).getTitle());
//下载图片
ImageLoader.getInstance().displayImage(datas.get(i).getThumbnail_pic_s(),viewHolder2.img1,options);
ImageLoader.getInstance().displayImage(datas.get(i).getThumbnail_pic_s02(),viewHolder2.img2,options);
return view;
}else{
ViewHolder1 viewHolder1;
if(view==null){
view=View.inflate(context,R.layout.item_one_image,null);
viewHolder1=new ViewHolder1();
viewHolder1.textView=view.findViewById(R.id.tv_title);
viewHolder1.img1=view.findViewById(R.id.img1);
view.setTag(viewHolder1);
}else{
viewHolder1=(ViewHolder1) view.getTag();
}
viewHolder1.textView.setText(datas.get(i).getTitle());
//下载图片
ImageLoader.getInstance().displayImage(datas.get(i).getThumbnail_pic_s(),viewHolder1.img1,options);
return view;
}
}
@Override
public int getViewTypeCount() {
return 3;
}
//position:条目的下标
@Override
public int getItemViewType(int position) {
//得到图片地址
String pics = datas.get(position).getThumbnail_pic_s();
String pic02 = datas.get(position).getThumbnail_pic_s02();
String pic03 = datas.get(position).getThumbnail_pic_s03();
if(pics!=null && pic02!=null && pic03!=null){
return THREE_IMAGE;//三张图类型
}else if(pics!=null && pic02!=null && pic03==null){
return TWO_IMAGE;//两张图的类型
}else if(pics!=null && pic02==null && pic03==null){
return ONE_IMAGE;//一张图的类型
}else{
return ONE_IMAGE;
}
}
class ViewHolder1{
TextView textView;
ImageView img1;
}
class ViewHolder2{
TextView textView;
ImageView img1;
ImageView img2;
}
class ViewHolder3{
TextView textView;
ImageView img1;
ImageView img2;
ImageView img3;
}
}
====================================================================
适配器中的布局:
item_one_image
<RelativeLayout android:layout_height="match_parent" android:layout_width="match_parent" xmlns:android="http://schemas.android.com/apk/res/android">
<TextView android:layout_height="wrap_content" android:layout_width="match_parent" android:id="@+id/tv_title"/>
<ImageView android:layout_height="80dp" android:layout_width="match_parent" android:id="@+id/img1" android:layout_centerHorizontal="true" android:layout_below="@+id/tv_title"/>
</RelativeLayout>
item_two_image
<RelativeLayout android:layout_height="match_parent" android:layout_width="match_parent" xmlns:android="http://schemas.android.com/apk/res/android">
<TextView android:layout_height="wrap_content" android:layout_width="match_parent" android:id="@+id/tv_title"/>
<LinearLayout android:layout_height="wrap_content" android:layout_width="match_parent" android:layout_below="@+id/tv_title" android:layout_centerHorizontal="true" android:orientation="horizontal">
<ImageView android:layout_height="80dp" android:layout_width="0dp" android:id="@+id/img1" android:layout_weight="1"/>
<ImageView android:layout_height="80dp" android:layout_width="0dp" android:id="@+id/img2" android:layout_weight="1"/>
</LinearLayout>
</RelativeLayout>
item_three_image
<RelativeLayout android:layout_height="match_parent" android:layout_width="match_parent" xmlns:android="http://schemas.android.com/apk/res/android">
<TextView android:layout_height="wrap_content" android:layout_width="match_parent" android:id="@+id/tv_title"/>
<LinearLayout android:layout_height="wrap_content" android:layout_width="match_parent" android:layout_below="@+id/tv_title" android:layout_centerHorizontal="true" android:orientation="horizontal">
<ImageView android:layout_height="80dp" android:layout_width="0dp" android:id="@+id/img1" android:layout_weight="1"/>
<ImageView android:layout_height="80dp" android:layout_width="0dp" android:id="@+id/img2" android:layout_weight="1"/>
<ImageView android:layout_height="80dp" android:layout_width="0dp" android:id="@+id/img3" android:layout_weight="1"/>
</LinearLayout>
</RelativeLayout>
==============================================================================================
imageloader:(记得导jar包universalimageloader)
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
// File file=getExternalCacheDir();//...data
File file= new File(Environment.getExternalStorageDirectory().getPath()+"/aaa");
//imgeloader的初使化
ImageLoaderConfiguration configuration=new ImageLoaderConfiguration.Builder(this)
.memoryCacheExtraOptions(480, 800)//缓存图片最大的长和宽
.threadPoolSize(2)//线程池的数量
.threadPriority(4)
.memoryCacheSize(5*1024*1024)//设置内存缓存区大小
.diskCacheSize(50*1024*1024)//设置sd卡缓存区大小
.diskCache(new UnlimitedDiscCache(file))//自定义sd缓存目录
.writeDebugLogs()//打印日志内容
.diskCacheFileNameGenerator(new Md5FileNameGenerator())//给缓存的文件名进行md5加密处理
.build();
ImageLoader.getInstance().init(configuration);
}
}