listview异步加载图片,上拉刷新

  以后有空就多写写博客,可以把思路理清楚,还是有好处的……之前只顾埋头写代码了,博客可以帮自己留下那些经验。

  话不多说,切入主题。这个demo使用了几个外包 下载地址分别是:http://download.csdn.net/detail/leozhu24/8641547,http://download.csdn.net/detail/leozhu24/8641533,http://download.csdn.net/detail/leozhu24/8641517,http://download.csdn.net/detail/leozhu24/8641491。

项目很简单,所以没添加什么注释 


 首先我们需要初始化异步下载使用的类,在 InitApplication 我们使用ImageLoaderConfiguration.Builder 的config设置该工具类的参数

public class InitApplication extends Application {

@Override
public void onCreate() {
super.onCreate();

initImageLoader();
}


private void initImageLoader() {

ImageLoaderConfiguration.Builder config = new ImageLoaderConfiguration.Builder(getApplicationContext());
config.memoryCacheExtraOptions(480, 800) // default = device screen dimensions  
//        .diskCacheExtraOptions(480, 800, CompressFormat.JPEG, 75, null)  
//        .taskExecutor(...)  
//        .taskExecutorForCachedImages(...)  
//        .threadPoolSize(Thread) // default  
        .threadPriority(Thread.NORM_PRIORITY - 2) // default  
        .tasksProcessingOrder(QueueProcessingType.FIFO) // default  
        .denyCacheImageMultipleSizesInMemory()  
//        .memoryCache(new LruMemoryCache(2 * 1024 * 1024))  
//        .memoryCacheSize(2 * 1024 * 1024)  
//        .memoryCacheSizePercentage(13) // default  
//        .diskCache(new UnlimitedDiscCache(cacheDir)) // default  
        .diskCacheSize(50 * 1024 * 1024)  
        .diskCacheFileCount(100)  
        .diskCacheFileNameGenerator(new HashCodeFileNameGenerator()) // default  
//        .imageDownloader(new BaseImageDownloader(context)) // default  
//        .imageDecoder(new BaseImageDecoder()) // default  
        .defaultDisplayImageOptions(DisplayImageOptions.createSimple()) // default  
        .writeDebugLogs()  
        .build();  

ImageLoader.getInstance().init(config.build());
}

}


接下来一个简单的主页面,点击显示listview的刷新页面,没什么好说的,点击按钮打开

public class MainActivity extends Activity implements OnClickListener {

Button bt01;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

init();
}


private void init() {
bt01 = (Button) findViewById(R.id.bt01);

bt01.setOnClickListener(this);
}


@Override
public void onClick(View v) {

Intent intent = null;

switch (v.getId()) {
case R.id.bt01:
intent = new Intent(MainActivity.this,ShowFragmentActivity.class);
intent.putExtra("Flag", Constants.Flag_listview_int);
break;


default:
break;
}

startActivity(intent);
}
}

打开的是一个FragmentActivity的界面,在这里我们可以通过上个页面传来的参数来显示不同的Fragment

public class ShowFragmentActivity extends FragmentActivity {

private String TAG = "ShowFragmentActivity";
private int flag;


@Override
protected void onCreate(Bundle arg0) {
super.onCreate(arg0);

//接收传递参数
Intent intent = getIntent();
flag = intent.getIntExtra("Flag", 0);

switchcase();
}

private void switchcase() {

Fragment fr = null;
String tag  = "";

switch (flag) {

case Constants.Flag_listview_int:
tag = ListviewFragment.class.getSimpleName();
fr = new ListviewFragment();
break;


default:
break;

}
getSupportFragmentManager().beginTransaction().add(android.R.id.content, fr,tag).commit();//打开界面
}


/* @Override
public View onCreateView(View parent, String name, Context context,
AttributeSet attrs) {

Log.e(TAG, "4_showfragment");
return super.onCreateView(parent, name, context, attrs);
}

@Override
public View onCreateView(String name, Context context, AttributeSet attrs) {
Log.e(TAG, "3_showfragment"); 
return super.onCreateView(name, context, attrs);

}*/
}

这里是ListviewFragment的界面


public class ListviewFragment extends Fragment implements
OnRefreshListener<ListView> {


String TAG = "ListviewFragment";
DisplayImageOptions options;
PullToRefreshListView pulltoR_listview;
private MyAdapter listviewAdapter;
private String[] morePics_url = new String[] {
"http://img3.imgtn.bdimg.com/it/u=3906148981,2815076670&fm=21&gp=0.jpg",
"http://images.csdn.net/20100506/logo.jpg",
"http://img1.imgtn.bdimg.com/it/u=1887538964,2552017407&fm=21&gp=0.jpg",
"http://www.c168c.com/images/attachement/jpg/site132/20110302/0016ecaae7b30ed8449e1c.jpg",
"http://pic20.nipic.com/20120506/3695685_100008655108_2.jpg" };
private ArrayList<String> arrayList;
private int time = 1;


@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);


options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.ic_stub)
.showImageForEmptyUri(R.drawable.ic_empty)
.showImageOnFail(R.drawable.ic_error).cacheInMemory(true)
.cacheOnDisk(true).considerExifParams(true)
.displayer(new RoundedBitmapDisplayer(20)).build();
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.listview_fragment, container,
false);


pulltoR_listview = (PullToRefreshListView) view
.findViewById(R.id.listview_fragment);


pulltoR_listview.setMode(Mode.BOTH);


initData();


listviewAdapter = new MyAdapter(arrayList);


pulltoR_listview.setAdapter(listviewAdapter);


pulltoR_listview.setOnRefreshListener(this);


return view;
}


private void initData() {


arrayList = new ArrayList<String>();
int length = Constants.image_urls.length;
for (int i = 0; i < length; i++) {
arrayList.add(Constants.image_urls[i]);
}
}


public class MyAdapter extends BaseAdapter {
ArrayList<String> arrayList = null;


public MyAdapter(ArrayList<String> arrayList) {
this.arrayList = arrayList;
}


@Override
public int getCount() {
return arrayList.size();
}


@Override
public Object getItem(int position) {
return arrayList.get(position);
}


@Override
public long getItemId(int position) {
return position;
}


@Override
public View getView(int position, View convertView, ViewGroup parent) {
Holder holder;
if (convertView == null) {
convertView = LayoutInflater.from(getActivity()).inflate(
R.layout.item_listview, null);
holder = new Holder();
holder.imageview = (ImageView) convertView
.findViewById(R.id.imageview);


convertView.setTag(holder);
} else {
holder = (Holder) convertView.getTag();
}
ImageLoader.getInstance().displayImage(arrayList.get(position),
holder.imageview, options);
// ImageLoader.getInstance().displayImage(image_urls[position],
// holder.imageview);


return convertView;
}
}


public class Holder {
ImageView imageview;


}


@Override
public void onRefresh(PullToRefreshBase<ListView> refreshView) {
String label = DateUtils.formatDateTime(getActivity(),
System.currentTimeMillis(), DateUtils.FORMAT_SHOW_TIME
| DateUtils.FORMAT_SHOW_DATE
| DateUtils.FORMAT_ABBREV_ALL);


// Update the LastUpdatedLabel
refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);


// Do work to refresh the list here.
new GetDataTask().execute();
}


private class GetDataTask extends AsyncTask<Void, Void, ArrayList<String>> {


@Override
protected ArrayList<String> doInBackground(Void... params) {
// Simulates a background job.
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
}
return arrayList;
}


@Override
protected void onPostExecute(ArrayList<String> result) {
if (time < 6) {
arrayList.add(morePics_url[time - 1]);
listviewAdapter.notifyDataSetChanged();


// Call onRefreshComplete when the list has been refreshed.
pulltoR_listview.onRefreshComplete();
time++;
} else {
Toast.makeText(getActivity(), "没有更多了", 0).show();
pulltoR_listview.onRefreshComplete();
}


super.onPostExecute(result);
}
}
}


这是常量类

public class Constants {

public static String Flag_listview = "listview";
public static String Flag_webview = "webview";
public static String Flag_scrollview = "scrollview";
public static String Flag_girdview = "girdview";
public static String Flag_pagerview = "pagerview";

public final static int Flag_listview_int = 1;
public final static int Flag_girdview_int = 2;
public final static int Flag_scrollview_int = 3;
public final static int Flag_webview_int = 4;
public final static int Flag_pagerview_int = 5;

public static String[] image_urls = new String[] {
"http://img3.3lian.com/2013/c4/10/d/17.jpg",
"http://pic1.ooopic.com/uploadfilepic/sheji/2008-11-01/OOOPIC_mwydsl_20081101dff3c2184fd5e90c.jpg",
"http://img.dapixie.com/uploads/allimg/120222/1-120222112321.jpg",
"http://tupian.enterdesk.com/2012/0621/gha/10/www.enterdesk.comq3.jpg.680.510.jpg",
"http://www.yyhh.com/file/upload/201012/08/23-25-05-70-1.jpg",
"http://img.dapixie.com/uploads/allimg/111105/1-111105145231.jpg",
"http://img.dapixie.com/uploads/allimg/120105/1-120105111451.jpg",
"http://img3.3lian.com/2013/c2/5/d/16.jpg",
"http://pic.58pic.com/uploadfilepic/sheying/2008-11-01/58PIC_mwydsl_200811017d3c6844ece512a9.jpg",
"http://pic.shejiben.com/caizhi/day_130123/20130123_ef6ffba6f20af7c231a1JppuoMNU9mBW.jpg",
"http://img5.douban.com/view/photo/photo/public/p1515362039.jpg",
"http://dmimg.5054399.com/allimg/xztuku/130924010.jpg",
"http://d.hiphotos.baidu.com/zhidao/pic/item/562c11dfa9ec8a13e028c4c0f603918fa0ecc0e4.jpg",
"http://img.redocn.com/201010/3/599750_1286086064SSce.jpg",
"http://img3.redocn.com/20091221/20091217_fa2a743db1f556f82b9asJ320coGmYFf.jpg",
"http://a2.att.hudong.com/04/58/300001054794129041580438110_950.jpg",
"http://pic8.nipic.com/20100728/2310993_092131041337_2.jpg",
"http://pic1.ooopic.com/uploadfilepic/sheji/2009-08-05/OOOPIC_SHIJUNHONG_20090805326b1a80e6c6aa6a.jpg",
"http://d.hiphotos.baidu.com/zhidao/wh%3D600%2C800/sign=324d313a233fb80e0c8469d106e10316/21a4462309f79052ab867a350ef3d7ca7bcbd51b.jpg",
"http://www.webmaster5u.com/upfiles/file/201107/20110723234012108.jpg",
"http://img.xiaba.cvimage.cn/4cbc56c1a57e26873c140000.jpg",
"http://pic1.ooopic.com/uploadfilepic/sheji/2009-05-05/OOOPIC_vip4_20090505079ae095187332ea.jpg",
"http://pic2.ooopic.com/01/26/61/83bOOOPIC72.jpg",
"http://pica.nipic.com/2007-11-12/20071112133257795_2.jpg",
"http://wenwen.soso.com/p/20090901/20090901120135-1666292770.jpg",
"http://wenwen.soso.com/p/20100314/20100314193521-535835454.jpg",
"http://pica.nipic.com/2007-12-18/200712189215503_2.jpg",
"http://img.taopic.com/uploads/allimg/110812/1820-110Q20K24526.jpg",
"http://wenwen.soso.com/p/20090901/20090901120441-1618619956.jpg",
"http://h.hiphotos.baidu.com/zhidao/pic/item/5bafa40f4bfbfbed0470471b78f0f736afc31fac.jpg",
"http://pic1.ooopic.com/uploadfilepic/sheji/2009-08-09/OOOPIC_SHIJUNHONG_20090809ad6104071d324dda.jpg",
"http://wenwen.soso.com/p/20090901/20090901120123-329341688.jpg",
"http://www.leawo.cn/attachment/201402/19/1880530_1392807424l5gk.jpg",
"http://pic1.ooopic.com/uploadfilepic/sheji/2009-08-12/OOOPIC_SHIJUNHONG_2009081248f16747c1659ceb.jpg",
"http://pica.nipic.com/2007-12-27/20071227195343914_2.jpg",
"",
};
}

下面是几个布局文件

activity_fragment.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="match_parent" >
    
    <fragment android:id="@+id/fragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
    


</RelativeLayout>


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" >


    <TextView
        android:id="@+id/tv"
        android:layout_centerHorizontal="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />


    <Button
        android:id="@+id/bt01"
        android:layout_below="@+id/tv"
        android:layout_width="150dp"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:text="@string/listview" />


  


</RelativeLayout>



item_listview.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="match_parent"
    android:orientation="vertical" >


    <ImageView
        android:id="@+id/imageview"
        android:layout_width="80dp"
        android:layout_height="80dp" />


</RelativeLayout>


listview_fragment.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="match_parent" >


<!--         android:id="@+id/pull_refresh_list" -->
    <com.handmark.pulltorefresh.library.PullToRefreshListView
        android:id="@+id/listview_fragment"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:cacheColorHint="#00000000"
        android:divider="#19000000"
        android:dividerHeight="4dp"
        android:fadingEdge="none"
        android:fastScrollEnabled="false"
        android:footerDividersEnabled="false"
        android:headerDividersEnabled="false"
        android:smoothScrollbar="true" />


</RelativeLayout>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值