listView图片与文字显示

来源:互联网 发布:域名找回 编辑:程序博客网 时间:2024/05/29 18:49

activity_main

<?xml version="1.0" encoding="utf-8"?><RelativeLayout    xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:app="http://schemas.android.com/apk/res-auto"    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"    android:layout_height="match_parent" tools:context="com.example.listview_request.MainActivity">    <ListView        android:id="@+id/lv"        android:layout_width="match_parent"        android:layout_height="match_parent" /></RelativeLayout>

item_bottom

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"    android:padding="10dp">    <TextView        android:id="@+id/text_title"        android:layout_width="match_parent"        android:layout_height="wrap_content" />    <ImageView        android:id="@+id/image_view"        android:layout_width="match_parent"        android:layout_height="200dp" /></LinearLayout>


item_left
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:padding="10dp"    android:orientation="horizontal">    <ImageView        android:id="@+id/image_view"        android:layout_width="100dp"        android:layout_height="100dp" />    <TextView        android:id="@+id/text_title"        android:layout_width="wrap_content"        android:layout_height="wrap_content"/></LinearLayout>

item_right
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:padding="10dp"    android:orientation="horizontal">    <TextView        android:id="@+id/text_title"        android:layout_width="0dp"        android:layout_weight="1"        android:layout_height="wrap_content" />    <ImageView        android:id="@+id/image_view"        android:layout_width="100dp"        android:layout_height="100dp" /></LinearLayout>

item_title
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:padding="10dp">    <TextView        android:id="@+id/text_title"        android:layout_width="wrap_content"        android:layout_height="wrap_content" /></LinearLayout>

item_View
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical">    <TextView        android:id="@+id/tv_title"        android:layout_width="match_parent"        android:layout_height="wrap_content" />    <ImageView        android:id="@+id/img"        android:layout_width="wrap_content"        android:layout_height="wrap_content"/></LinearLayout>

bewn
MyTask
package com.example.listview_request.Utils;import android.os.AsyncTask;import java.io.IOException;import java.io.InputStream;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;/** * Created by ass on 2017/10/12. */public class MyTask extends AsyncTask<String,Void,String>{    private Icallbacks icallbacks;    private MyTask(){}    public MyTask(Icallbacks icallbacks) {        this.icallbacks = icallbacks;    }    @Override    protected String doInBackground(String... params) {        String str="";        try {            URL url=new URL(params[0]);            HttpURLConnection connection = (HttpURLConnection) url.openConnection();            connection.setRequestMethod("GET");            connection.setReadTimeout(5000);            connection.setConnectTimeout(5000);            if(connection.getResponseCode()==200){                InputStream inputStream = connection.getInputStream();                str=StreamToString.streamToStr(inputStream,"utf-8");            }        } catch (MalformedURLException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }        return str;    }    @Override    protected void onPostExecute(String s) {        super.onPostExecute(s);        icallbacks.updateUiByjson(s);    }    public interface Icallbacks{        void updateUiByjson(String jsonstr);    }}

StreamToString 
package com.example.listview_request.Utils;import java.io.BufferedReader;import java.io.InputStream;import java.io.InputStreamReader;/** * Created by ass on 2017/10/12. */public class StreamToString {    public static String streamToStr(InputStream inputStream, String chartSet){        StringBuilder builder = new StringBuilder();        try {            String con;            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, chartSet));            while ((con=reader.readLine())!=null){                builder.append(con);            }            reader.close();            return builder.toString();        } catch (Exception e) {            e.printStackTrace();        }        return "";    }}

MyApplication 
package com.example.listview_request;import android.app.Application;import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache;import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;import com.nostra13.universalimageloader.core.ImageLoader;import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;import java.io.File;/** * Created by ass on 2017/10/12. */public class MyApplication extends Application{    @Override    public void onCreate() {        super.onCreate();        File cachefile = getExternalCacheDir();        ImageLoaderConfiguration configuration=new ImageLoaderConfiguration.Builder(this)                .memoryCacheExtraOptions(480, 800)//缓存图片最大的长和宽                .threadPoolSize(2)//线程池的数量                .threadPriority(4)                .memoryCacheSize(2*1024*1024)//设置内存缓存区大小                .diskCacheSize(20*1024*1024)//设置sd卡缓存区大小                .diskCache(new UnlimitedDiscCache(cachefile))//自定义缓存目录                .writeDebugLogs()//打印日志内容                .diskCacheFileNameGenerator(new Md5FileNameGenerator())//给缓存的文件名进行md5加密处理                .build();        ImageLoader.getInstance().init(configuration);    }}

MainActivity
package com.example.listview_request;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.widget.ListView;import com.example.listview_request.Utils.MyTask;import com.google.gson.Gson;import java.util.List;public class MainActivity extends AppCompatActivity {    private ListView lv;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        lv=(ListView) findViewById(R.id.lv);        MyTask myTask = new MyTask(new MyTask.Icallbacks() {            @Override            public void updateUiByjson(String jsonstr) {                Gson gson = new Gson();                DataBean result = gson.fromJson(jsonstr, DataBean.class);                List<DataBean.ResultBean.ListBean> datas = result.getResult().getList();                lv.setAdapter(new MyAdapter(MainActivity.this,datas));            }        });        myTask.execute("http://v.juhe.cn/weixin/query?key=88f7bbc507e3ecacfaeab2b47dd8936f&ps=30");    }}
Adapter
package com.example.listview_request;import android.content.Context;import android.graphics.Bitmap;import android.view.View;import android.view.ViewGroup;import android.widget.BaseAdapter;import android.widget.ImageView;import android.widget.TextView;import com.nostra13.universalimageloader.core.DisplayImageOptions;import com.nostra13.universalimageloader.core.ImageLoader;import java.util.List;/** * Created by ass on 2017/10/12. */public class MyAdapter extends BaseAdapter{    private Context context;    private List<DataBean.ResultBean.ListBean> datas;    private int TYTLE_ONLY=0;//只有文字的形式    private int IMAGE_LEFT = 1;//表示图片在左边,文字在右边    private int IMAGE_RIGHT = 2;//表示图片在右边,文字在左边    private int IMAGE_BOTTOM = 3;//表示文字在上边,图片在下面    private DisplayImageOptions options;    public MyAdapter(Context context,List<DataBean.ResultBean.ListBean>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)//设置图片格式                .build();    }    @Override    public int getItemViewType(int position) {        if(position%4==0){            return TYTLE_ONLY;        }else if(position%4==1){            return IMAGE_LEFT;        }else if(position%4==2){            return IMAGE_RIGHT;        }        return IMAGE_BOTTOM;    }    @Override    public int getViewTypeCount() {        return 4;    }    @Override    public int getCount() {        return datas.size();    }    @Override    public Object getItem(int position) {        return datas.get(position);    }    @Override    public long getItemId(int position) {        return position;    }    @Override    public View getView(int position, View convertView, ViewGroup parent) {        int type=getItemViewType(position);        if(type==TYTLE_ONLY){            ViewHolder holder;            if(convertView==null){                convertView=View.inflate(context,R.layout.list_view,null);                holder=new ViewHolder();                holder.tvTitle=(TextView) convertView.findViewById(R.id.tv_title);                convertView.setTag(holder);            }else{                holder=(ViewHolder) convertView.getTag();            }            holder.tvTitle.setText(datas.get(position).getTitle());        }else if(type==IMAGE_LEFT){            ViewHolderLeft holder;            if(convertView==null){                convertView=View.inflate(context,R.layout.item_left,null);                holder=new ViewHolderLeft();                holder.tvTitle=(TextView) convertView.findViewById(R.id.text_title);                holder.imageView= (ImageView) convertView.findViewById(R.id.image_view);                convertView.setTag(holder);            }else{                holder=(ViewHolderLeft) convertView.getTag();            }            holder.tvTitle.setText(datas.get(position).getTitle());            ImageLoader.getInstance().displayImage(datas.get(position).getFirstImg(),holder.imageView,options);        }else if(type==IMAGE_RIGHT){            ViewHolderRight holder;            if(convertView==null){                convertView=View.inflate(context,R.layout.item_right,null);                holder=new ViewHolderRight();                holder.tvTitle=(TextView) convertView.findViewById(R.id.text_title);                holder.imageView= (ImageView) convertView.findViewById(R.id.image_view);                convertView.setTag(holder);            }else{                holder=(ViewHolderRight) convertView.getTag();            }            holder.tvTitle.setText(datas.get(position).getTitle());            ImageLoader.getInstance().displayImage(datas.get(position).getFirstImg(),holder.imageView,options);        }else{            ViewHolderBottom holder;            if(convertView==null){                convertView=View.inflate(context,R.layout.item_bottom,null);                holder=new ViewHolderBottom();                holder.tvTitle=(TextView) convertView.findViewById(R.id.text_title);                holder.imageView= (ImageView) convertView.findViewById(R.id.image_view);                convertView.setTag(holder);            }else{                holder=(ViewHolderBottom) convertView.getTag();            }            holder.tvTitle.setText(datas.get(position).getTitle());            ImageLoader.getInstance().displayImage(datas.get(position).getFirstImg(),holder.imageView,options);        }        return convertView;    }    class ViewHolder{        TextView tvTitle;    }    class ViewHolderLeft{        TextView tvTitle;        ImageView imageView;    }    class ViewHolderRight{        TextView tvTitle;        ImageView imageView;    }    class ViewHolderBottom{        TextView tvTitle;        ImageView imageView;    }}

原创粉丝点击