当前位置: 代码迷 >> 综合 >> 利用 Android异步任务AsyncTask 实现ListView 图文混排
  详细解决方案

利用 Android异步任务AsyncTask 实现ListView 图文混排

热度:18   发布时间:2023-12-18 22:41:18.0

1.布局文件

 activity_main.xml  

<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" ><ListView android:id="@+id/lv_main"    android:layout_width="match_parent"android:layout_height="match_parent"></ListView></RelativeLayout>
item_layout.xml
<?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="wrap_content"android:orientation="horizontal" ><ImageView android:id="@+id/tv_icon"android:layout_width="62dp"android:layout_height="62dp"/><LinearLayout android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"android:gravity="center"android:paddingLeft="4dp"><TextView android:id="@+id/tv_title"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="标题"android:textSize="15sp"android:maxLines="1"/><TextViewandroid:id="@+id/tv_content"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="内容"android:textSize="10sp"android:maxLines="3"/>    </LinearLayout></LinearLayout>

MainActivity.java

package com.example.asynctask2;import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.widget.ListView;public class MainActivity extends Activity {private ListView mListView;private String URL="http://www.imooc.com/api/teacher?type=4&num=30";@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);mListView=(ListView) findViewById(R.id.lv_main);new NewAsyncTask().execute(URL);//执行异步任务}/*** 获取json数据* @param url* @return*/private List<NewBean> getJsonDate(String url){List<NewBean> newlist=new ArrayList<NewBean>();try {String jsonString=readStram(new URL(url).openStream());//Log.i("json",jsonString);JSONObject jsonObject;NewBean newbean;try {//解析jsonjsonObject=new JSONObject(jsonString);JSONArray jsonArray=jsonObject.getJSONArray("data");for(int i=0;i<jsonArray.length();i++){jsonObject=jsonArray.getJSONObject(i);newbean=new NewBean();newbean.IconUrl=jsonObject.getString("picSmall");newbean.newtitle=jsonObject.getString("name");newbean.newcontent=jsonObject.getString("description");newlist.add(newbean);}} catch (JSONException e) { e.printStackTrace();}} catch (IOException e) { e.printStackTrace();}return newlist;}private String readStram(InputStream is){InputStreamReader isr;String result="";try {String line="";isr=new InputStreamReader(is,"utf-8");BufferedReader br=new BufferedReader(isr);while((line=br.readLine())!=null){result+=line;}} catch (UnsupportedEncodingException e) {e.printStackTrace();}catch(IOException e){e.printStackTrace();}return result;}class NewAsyncTask extends AsyncTask<String, Void,List<NewBean>>{@Overrideprotected List<NewBean> doInBackground(String... params) {return getJsonDate(params[0]);}@Overrideprotected void onPostExecute(List<NewBean> result) {// TODO Auto-generated method stubsuper.onPostExecute(result);NewAdapter newadpter=new NewAdapter(MainActivity.this, result);mListView.setAdapter(newadpter); }}}


NewBean.java

package com.example.asynctask2;public class NewBean {public String IconUrl;public String newtitle;public String newcontent;}


NewAdapter.java

package com.example.asynctask2;import java.util.List;import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;public class NewAdapter  extends BaseAdapter{private List<NewBean> mlist;private LayoutInflater mInflater;public NewAdapter(Context context,List<NewBean> data){mlist=data;mInflater=LayoutInflater.from(context);}@Overridepublic int getCount() {return mlist.size();}@Overridepublic Object getItem(int position) {return mlist.get(position);}@Overridepublic long getItemId(int position) {return position;}@Overridepublic View getView(int position, View convertView, ViewGroup parent) {ViewHolder viewHolder=null;if(convertView==null){viewHolder=new ViewHolder();convertView=mInflater.inflate(R.layout.item_layout, null);viewHolder.ivIcon=(ImageView) convertView.findViewById(R.id.tv_icon);viewHolder.tvTitle=(TextView) convertView.findViewById(R.id.tv_title);viewHolder.tvContent=(TextView) convertView.findViewById(R.id.tv_content);convertView.setTag(viewHolder);}else{viewHolder=(ViewHolder) convertView.getTag();}viewHolder.ivIcon.setImageResource(R.drawable.ic_launcher);String url= mlist.get(position).IconUrl;viewHolder.ivIcon.setTag(url);new ImageLoder().showImageByThread(viewHolder.ivIcon,url);viewHolder.tvTitle.setText(mlist.get(position).newtitle);viewHolder.tvContent.setText(mlist.get(position).newcontent);return convertView;}class ViewHolder{public TextView tvTitle,tvContent;public ImageView ivIcon;}}

ImageLoder.java

package com.example.asynctask2;import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.widget.ImageView;public class ImageLoder {private ImageView mImageView;private String mUrl;Handler handler=new Handler(){public void handleMessage(android.os.Message msg) {super.handleMessage(msg);if(mImageView.getTag().equals(mUrl)){mImageView.setImageBitmap((Bitmap) msg.obj);}};};public void showImageByThread(ImageView imageview,final String url){mImageView=imageview;mUrl=url;new Thread(){public void run() {super.run();Bitmap bitmap=getBitmapFromURL(url);Message msg=Message.obtain();msg.obj=bitmap;handler.sendMessage(msg);}}.start();}public Bitmap getBitmapFromURL(String urlString){Bitmap bitmap;InputStream is=null;try {URL url=new URL(urlString);HttpURLConnection connection=(HttpURLConnection) url.openConnection();is=new BufferedInputStream(connection.getInputStream());bitmap=BitmapFactory.decodeStream(is);connection.disconnect();return bitmap;} catch (java.io.IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}finally{try {is.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}return null;}
}



  相关解决方案