(一个常用的案例)Fragment xlistview pull 网络请求 刷新分页加载 ImageLoader

来源:互联网 发布:用网络发短信的软件 编辑:程序博客网 时间:2024/04/30 05:12


                               我们最常用的就是网络请求啦,各种各样的柔和在一起,下面我们来看看这个案例的实现:


1.———————主函数的布局 activity_main.xml—————————— 一定要记得加权限、配置

                              *******用的是xlistview哦************

<span style="font-size:18px;"><LinearLayout 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:orientation="vertical"     >    <android.support.v4.view.ViewPager        android:layout_weight="1"        android:layout_height="match_parent"        android:layout_width="fill_parent"        android:id="@+id/vp"        />    <RadioGroup         android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:orientation="horizontal"        android:id="@+id/rg"        >                <RadioButton             android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="动弹"            android:button="@null"            android:id="@+id/rb_dongtan"            android:textSize="17sp"            android:textColor="#339933"            android:background="#f00"            />        <RadioButton             android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="博客"            android:button="@null"            android:id="@+id/rb_boke"             android:textSize="17sp"             android:layout_marginLeft="100dp"            />        <RadioButton             android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="推荐"            android:button="@null"            android:id="@+id/rb_tuijian"             android:layout_marginLeft="100dp"             android:textSize="17sp"            />    </RadioGroup></LinearLayout></span>

2.——————————————主函数 MainActivity.java——————————————


<span style="font-size:18px;">import com.bwie.fragment.Fragment1;import com.bwie.fragment.Fragment2;import android.app.Activity;import android.graphics.Color;import android.os.Bundle;import android.support.v4.app.Fragment;import android.support.v4.app.FragmentActivity;import android.support.v4.app.FragmentPagerAdapter;import android.support.v4.view.ViewPager;import android.support.v4.view.ViewPager.OnPageChangeListener;import android.view.Menu;import android.view.MenuItem;import android.widget.RadioButton;import android.widget.RadioGroup;import android.widget.RadioGroup.OnCheckedChangeListener;public class MainActivity extends FragmentActivity {private ViewPager vp;private RadioButton rb1;private RadioButton rb2;private RadioButton rb3;private RadioGroup rg;private String url="http://www.oschina.net/action/api/blog_list?type=latest&pageSize=15";private String url1="http://www.oschina.net/action/api/blog_list?type=recommend&pageSize=15";@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);//找取控件initId();//设置vp滑动事件vp_setting();//设置rg的点击事件rg_setting();//设置视图vp_shitu();}private void vp_shitu() {// TODO Auto-generated method stubvp.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {@Overridepublic int getCount() {// TODO Auto-generated method stubreturn 3;}/** * 其中  博客和推荐共用一个fragment2 */@Overridepublic Fragment getItem(int arg0) {// TODO Auto-generated method stubFragment f=null;switch (arg0) {case 0:f=new Fragment1();break;case 1:f=new Fragment2(url);break;case 2:f=new Fragment2(url1);break;default:break;}return f;}});}private void rg_setting() {// TODO Auto-generated method stubrg.setOnCheckedChangeListener(new OnCheckedChangeListener() {@Overridepublic void onCheckedChanged(RadioGroup group, int checkedId) {// TODO Auto-generated method stubswitch (checkedId) {case R.id.rb_dongtan://选中页面1vp.setCurrentItem(0);break;case R.id.rb_boke://选中页面1vp.setCurrentItem(1);break;case R.id.rb_tuijian://选中页面1vp.setCurrentItem(2);break;default:break;}}});}@SuppressWarnings("deprecation")private void vp_setting() {// TODO Auto-generated method stubvp.setOnPageChangeListener(new OnPageChangeListener() {@Overridepublic void onPageSelected(int arg0) {// TODO Auto-generated method stubswitch (arg0) {case 0://选中rb1rg.check(R.id.rb_dongtan);//改变颜色rb1.setTextColor(Color.GREEN);rb2.setTextColor(Color.BLACK);rb3.setTextColor(Color.BLACK);//改变北京rb1.setBackgroundColor(Color.RED);rb2.setBackgroundColor(Color.WHITE);rb3.setBackgroundColor(Color.WHITE);break;case 1://选中rb1rg.check(R.id.rb_boke);//改变颜色rb2.setTextColor(Color.GREEN);rb1.setTextColor(Color.BLACK);rb3.setTextColor(Color.BLACK);rb2.setBackgroundColor(Color.RED);rb1.setBackgroundColor(Color.WHITE);rb3.setBackgroundColor(Color.WHITE);break;case 2://选中rb1rg.check(R.id.rb_tuijian);//改变颜色rb3.setTextColor(Color.GREEN);rb2.setTextColor(Color.BLACK);rb1.setTextColor(Color.BLACK);rb3.setBackgroundColor(Color.RED);rb2.setBackgroundColor(Color.WHITE);rb1.setBackgroundColor(Color.WHITE);break;default:break;}}@Overridepublic void onPageScrolled(int arg0, float arg1, int arg2) {// TODO Auto-generated method stub}@Overridepublic void onPageScrollStateChanged(int arg0) {// TODO Auto-generated method stub}});}private void initId() {vp = (ViewPager) findViewById(R.id.vp);rg = (RadioGroup) findViewById(R.id.rg);rb1 = (RadioButton) findViewById(R.id.rb_dongtan);rb2 = (RadioButton) findViewById(R.id.rb_boke);rb3 = (RadioButton) findViewById(R.id.rb_tuijian);}}</span>


3.———————————————Fragment1.java——————————————————

<span style="font-size:18px;">import java.io.ByteArrayInputStream;import java.util.ArrayList;import java.util.List;import me.maxwin.view.XListView;import me.maxwin.view.XListView.IXListViewListener;import org.xmlpull.v1.XmlPullParser;import org.xmlpull.v1.XmlPullParserException;import com.bwie.adapter.MyListAdapter;import com.bwie.bean.Reason_Dongtan;import com.bwie.test.R;import com.lidroid.xutils.HttpUtils;import com.lidroid.xutils.exception.HttpException;import com.lidroid.xutils.http.ResponseInfo;import com.lidroid.xutils.http.callback.RequestCallBack;import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;import android.os.Bundle;import android.os.Handler;import android.support.v4.app.Fragment;import android.util.Log;import android.util.Xml;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;public class Fragment1 extends Fragment implements IXListViewListener{private View v;private ByteArrayInputStream array;private int index=0;//记录每次加载的为值private boolean isRefresh = false;  private List<Reason_Dongtan> list1=new ArrayList<Reason_Dongtan>();private Handler handler=new Handler(){private MyListAdapter adapter;public void handleMessage(android.os.Message msg) {switch (msg.what) {case 1://解析数据List<Reason_Dongtan> list = xml_jiexi(array);if(isRefresh){list1.clear();}list1.addAll(list);if(adapter==null){adapter = new MyListAdapter(getActivity(),list1);xlistview.setAdapter(adapter);}else{//刷新适配器adapter.notifyDataSetChanged();}onLoad();//打印Log.d("list1", list.toString());break;default:break;}};};private Reason_Dongtan r1;private XListView xlistview;@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {// TODO Auto-generated method stubv=inflater.inflate(R.layout.fragment_dongtan, null);return v;}protected List<Reason_Dongtan> xml_jiexi(ByteArrayInputStream array2) {// TODO Auto-generated method stubList<Reason_Dongtan> list=new ArrayList<Reason_Dongtan>();//使用pull解析XmlPullParser parser = Xml.newPullParser();try {parser.setInput(array2, "utf-8");//开始解析int type = parser.getEventType();while(type!=XmlPullParser.END_DOCUMENT){//获取nameString name = parser.getName();switch (type) {//开始节点case XmlPullParser.START_TAG:if(name.equals("tweet")){r1 = new Reason_Dongtan();}else if(name.equals("portrait")){r1.setPortrait(parser.nextText());}else if(name.equals("author")){r1.setAuthor(parser.nextText());}else if(name.equals("body")){r1.setBody(parser.nextText());}else if(name.equals("pubDate")){r1.setPubDate(parser.nextText());}break;case XmlPullParser.END_TAG:if(name.equals("tweet")){//存集合list.add(r1);//清空r1=null;}break;default:break;}//循环type=parser.next();}} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}return list;}@Overridepublic void onActivityCreated(Bundle savedInstanceState) {// TODO Auto-generated method stubsuper.onActivityCreated(savedInstanceState);//找取控件initId();//请求数据getData(index);}private void initId() {xlistview = (XListView) v.findViewById(R.id.xlistview);xlistview.setPullLoadEnable(true);xlistview.setPullRefreshEnable(true);xlistview.setXListViewListener(this);}private void onLoad(){xlistview.stopRefresh();xlistview.stopLoadMore();xlistview.setRefreshTime("刚刚才刷新的");}private void getData(int num) {// TODO Auto-generated method stubHttpUtils utils=new HttpUtils();utils.configTimeout(5000);//设置超时时间//请求数据utils.send(HttpMethod.GET, "http://www.oschina.net/action/api/tweet_list?Uid=0&pageIndex="+num+"&pageSize=15", new RequestCallBack<String>() {@Overridepublic void onFailure(HttpException arg0, String arg1) {// TODO Auto-generated method stub}@Overridepublic void onSuccess(ResponseInfo<String> arg0) {String reultData = arg0.result;array = new ByteArrayInputStream(reultData.getBytes());//通过handler更新handler.sendEmptyMessage(1);}});}//刷新@Overridepublic void onRefresh() {// TODO Auto-generated method stubindex=0;isRefresh=true;getData(index);}//加载@Overridepublic void onLoadMore() {// TODO Auto-generated method stubindex++;isRefresh=false;getData(index);}}</span>

4.———————————————Fragment2.java——————————————————

<span style="font-size:18px;">import java.io.ByteArrayInputStream;import java.util.ArrayList;import java.util.List;import me.maxwin.view.XListView;import me.maxwin.view.XListView.IXListViewListener;import org.xmlpull.v1.XmlPullParser;import org.xmlpull.v1.XmlPullParserException;import com.bwie.adapter.MyBokeListAdapter;import com.bwie.adapter.MyListAdapter;import com.bwie.bean.Reason_BokeTuijian;import com.bwie.bean.Reason_Dongtan;import com.bwie.test.R;import com.lidroid.xutils.HttpUtils;import com.lidroid.xutils.exception.HttpException;import com.lidroid.xutils.http.ResponseInfo;import com.lidroid.xutils.http.callback.RequestCallBack;import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;import android.os.Bundle;import android.os.Handler;import android.support.v4.app.Fragment;import android.util.Log;import android.util.Xml;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;public class Fragment2 extends Fragment implements IXListViewListener{private String urlc;private View v;private ByteArrayInputStream array;private int index=0;//记录每次加载的为值private boolean isRefresh = false;  private List<Reason_BokeTuijian> list1=new ArrayList<Reason_BokeTuijian>();public Fragment2(String urlc) {super();this.urlc = urlc;}private Handler handler=new Handler(){private MyBokeListAdapter adapter;public void handleMessage(android.os.Message msg) {switch (msg.what) {case 1://解析数据List<Reason_BokeTuijian> list = xml_jiexi(array);if(isRefresh){list1.clear();}list1.addAll(list);if(adapter==null){adapter = new MyBokeListAdapter(getActivity(),list1);xlistview.setAdapter(adapter);}else{//刷新适配器adapter.notifyDataSetChanged();}onLoad();//打印Log.d("list1", list.toString());break;default:break;}};};private Reason_BokeTuijian r1;private XListView xlistview;@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {// TODO Auto-generated method stubv=inflater.inflate(R.layout.fragment_boke, null);return v;}protected List<Reason_BokeTuijian> xml_jiexi(ByteArrayInputStream array2) {// TODO Auto-generated method stubList<Reason_BokeTuijian> list=new ArrayList<Reason_BokeTuijian>();//使用pull解析XmlPullParser parser = Xml.newPullParser();try {parser.setInput(array2, "utf-8");//开始解析int type = parser.getEventType();while(type!=XmlPullParser.END_DOCUMENT){//获取nameString name = parser.getName();switch (type) {//开始节点case XmlPullParser.START_TAG:if(name.equals("blog")){r1 = new Reason_BokeTuijian();}else if(name.equals("title")){r1.setTitle(parser.nextText());}else if(name.equals("authorname")){r1.setAuthorname(parser.nextText());}else if(name.equals("body")){r1.setBody(parser.nextText());}else if(name.equals("pubDate")){r1.setPubDate(parser.nextText());}break;case XmlPullParser.END_TAG:if(name.equals("blog")){//存集合list.add(r1);//清空r1=null;}break;default:break;}//循环type=parser.next();}} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}return list;}@Overridepublic void onActivityCreated(Bundle savedInstanceState) {// TODO Auto-generated method stubsuper.onActivityCreated(savedInstanceState);//找取控件initId();//请求数据getData(index);}private void initId() {xlistview = (XListView) v.findViewById(R.id.xlistview1);xlistview.setPullLoadEnable(true);xlistview.setPullRefreshEnable(true);xlistview.setXListViewListener(this);}private void onLoad(){xlistview.stopRefresh();xlistview.stopLoadMore();xlistview.setRefreshTime("刚刚才刷新的");}private void getData(int num) {// TODO Auto-generated method stubHttpUtils utils=new HttpUtils();utils.configTimeout(5000);//设置超时时间//请求数据utils.send(HttpMethod.GET, urlc+"&pageIndex="+num, new RequestCallBack<String>() {@Overridepublic void onFailure(HttpException arg0, String arg1) {// TODO Auto-generated method stub}@Overridepublic void onSuccess(ResponseInfo<String> arg0) {String reultData = arg0.result;array = new ByteArrayInputStream(reultData.getBytes());//通过handler更新handler.sendEmptyMessage(1);}});}//刷新@Overridepublic void onRefresh() {// TODO Auto-generated method stubindex=0;isRefresh=true;getData(index);}//加载@Overridepublic void onLoadMore() {// TODO Auto-generated method stubindex++;isRefresh=false;getData(index);}}</span>


5.————————————————适配器——MyBokeListAdapter.java—————————————————

<span style="font-size:18px;">import java.util.List;import com.bwie.bean.Reason_BokeTuijian;import com.bwie.test.R;import android.content.Context;import android.view.View;import android.view.ViewGroup;import android.widget.BaseAdapter;import android.widget.TextView;public class MyBokeListAdapter extends BaseAdapter {private Context context;private List<Reason_BokeTuijian> list;private ViewHolder holder;public MyBokeListAdapter(Context context, List<Reason_BokeTuijian> list) {super();this.context = context;this.list = list;}@Overridepublic int getCount() {// TODO Auto-generated method stubreturn list.size();}@Overridepublic Object getItem(int position) {// TODO Auto-generated method stubreturn list.get(position);}@Overridepublic long getItemId(int position) {// TODO Auto-generated method stubreturn position;}@Overridepublic View getView(int position, View convertView, ViewGroup parent) {// TODO Auto-generated method stubif(convertView==null){convertView=View.inflate(context, R.layout.boke_item, null);holder = new ViewHolder();holder.boke_author=(TextView) convertView.findViewById(R.id.boke_author);holder.boke_nei=(TextView) convertView.findViewById(R.id.boke_nei);holder.boke_time=(TextView) convertView.findViewById(R.id.boke_time);holder.boke_title=(TextView) convertView.findViewById(R.id.boke_title);convertView.setTag(holder);}else{holder =(ViewHolder) convertView.getTag();}holder.boke_author.setText(list.get(position).getAuthorname());holder.boke_nei.setText(list.get(position).getBody());holder.boke_time.setText(list.get(position).getPubDate());holder.boke_title.setText(list.get(position).getTitle());return convertView;}class ViewHolder{TextView boke_title,boke_author,boke_time,boke_nei;}}</span>


6.——————————————适配器—MyListAdapter.java——————————————————

<span style="font-size:18px;">import java.util.List;import com.bwie.bean.Reason_Dongtan;import com.bwie.test.R;import com.lidroid.xutils.BitmapUtils;import com.nostra13.universalimageloader.core.ImageLoader;import android.content.Context;import android.view.View;import android.view.ViewGroup;import android.widget.BaseAdapter;import android.widget.ImageView;import android.widget.TextView;public class MyListAdapter extends BaseAdapter {private Context context;private List<Reason_Dongtan> list;private ViewHolder holder;public MyListAdapter(Context context, List<Reason_Dongtan> list) {super();this.context = context;this.list = list;}@Overridepublic int getCount() {// TODO Auto-generated method stubreturn list.size();}@Overridepublic Object getItem(int position) {// TODO Auto-generated method stubreturn list.get(position);}@Overridepublic long getItemId(int position) {// TODO Auto-generated method stubreturn position;}/** * 优化 */@Overridepublic View getView(int position, View convertView, ViewGroup parent) {// TODO Auto-generated method stubif(convertView==null){convertView=View.inflate(context, R.layout.xlistview_item, null);holder = new ViewHolder();holder.item_iv=(ImageView) convertView.findViewById(R.id.item_iv);holder.item_body=(TextView) convertView.findViewById(R.id.item_body);holder.item_author=(TextView) convertView.findViewById(R.id.item_author);holder.item_time=(TextView) convertView.findViewById(R.id.item_time);convertView.setTag(holder);}else{holder=(ViewHolder) convertView.getTag();}holder.item_author.setText(list.get(position).getAuthor());holder.item_body.setText(list.get(position).getBody());holder.item_time.setText(list.get(position).getPubDate());//ImageLoader加载图片ImageLoader.getInstance().displayImage(list.get(position).getPortrait(), holder.item_iv);return convertView;}class ViewHolder{ImageView item_iv;TextView item_body,item_author,item_time;}}</span>


7.—————————————fragment_dongtan.xml————————————————————


<span style="font-size:18px;"><?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" >        <me.maxwin.view.XListView        android:layout_width="fill_parent"        android:layout_height="match_parent"        android:id="@+id/xlistview"        />    </LinearLayout></span>


8.———————————————fragment_boke.xml——————————————————

<span style="font-size:18px;"><?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" >        <me.maxwin.view.XListView        android:layout_width="fill_parent"        android:layout_height="match_parent"        android:id="@+id/xlistview1"        />    </LinearLayout></span>


9.————————————————boke_item.xml—————————————————


<span style="font-size:18px;"><?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" >           <TextView        android:layout_width="wrap_content"       android:layout_height="wrap_content"       android:text="标题"       android:id="@+id/boke_title"       />   <TextView       android:id="@+id/boke_author"       android:layout_width="wrap_content"       android:layout_height="wrap_content"       android:layout_marginLeft="100dp"       android:text="作者" />   <TextView       android:id="@+id/boke_time"       android:layout_width="wrap_content"       android:layout_height="wrap_content"       android:layout_marginLeft="190dp"       android:textSize="12sp"       android:text="时间" />   <TextView       android:id="@+id/boke_nei"       android:layout_width="wrap_content"       android:layout_height="wrap_content"       android:layout_alignParentLeft="true"       android:layout_below="@+id/boke_author"       android:layout_marginTop="16dp"       android:maxLines="1"       android:text="内容" /></RelativeLayout></span>


10.——————————————xlistview_item.xml———————————————————

<span style="font-size:18px;"><?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"     >        <ImageView         android:layout_width="50dp"        android:layout_height="50dp"        android:src="@drawable/ic_launcher"        android:id="@+id/item_iv"        />    <TextView        android:id="@+id/item_author"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignParentTop="true"        android:layout_marginLeft="29dp"        android:layout_toRightOf="@+id/item_iv"        android:text="作者" />    <TextView        android:id="@+id/item_body"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignBottom="@+id/item_iv"        android:layout_alignLeft="@+id/item_author"        android:ellipsize="end"        android:maxLines="1"        android:text="简介" />    <TextView        android:id="@+id/item_time"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignParentRight="true"        android:layout_alignParentTop="true"        android:layout_marginRight="19dp"        android:textSize="12sp"        android:maxLines="1"        android:text="时间" /></RelativeLayout></span>


11.————————————实体类bean———Reason_BokeTuijian.java——————————————————

<span style="font-size:18px;">public class Reason_BokeTuijian {private String title;private String body;private String pubDate;private String authorname;public String getTitle() {return title;}public void setTitle(String title) {this.title = title;}public String getBody() {return body;}public void setBody(String body) {this.body = body;}public String getPubDate() {return pubDate;}public void setPubDate(String pubDate) {this.pubDate = pubDate;}public String getAuthorname() {return authorname;}public void setAuthorname(String authorname) {this.authorname = authorname;}}</span>



12.————————————实体类bean——Reason_Dongtan.java———————————————————

<span style="font-size:18px;">/** * 动弹bean类 * @author 明天更美好 * */public class Reason_Dongtan {private String portrait;//图片private String author;private String body;private String pubDate;public String getPortrait() {return portrait;}public void setPortrait(String portrait) {this.portrait = portrait;}public String getAuthor() {return author;}public void setAuthor(String author) {this.author = author;}public String getBody() {return body;}public void setBody(String body) {this.body = body;}public String getPubDate() {return pubDate;}public void setPubDate(String pubDate) {this.pubDate = pubDate;}@Overridepublic String toString() {return "Reason_Dongtan [portrait=" + portrait + ", author=" + author+ ", body=" + body + ", pubDate=" + pubDate + "]";}}</span>



13.——————————工具类———MyApplication.java—————记得配置name————————————

<span style="font-size:18px;">import com.nostra13.universalimageloader.core.ImageLoader;import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;import android.app.Application;public class MyApplication extends Application{@Overridepublic void onCreate() {// TODO Auto-generated method stubsuper.onCreate();//ImageLoader加载图片ImageLoaderConfiguration con=new ImageLoaderConfiguration.Builder(this).writeDebugLogs().build();ImageLoader.getInstance().init(con);}}</span>

                                     —————————到这里就搞定啦——————————



0 0
原创粉丝点击