Pulltorefresh上拉加载下拉刷新
程序员文章站
2024-03-17 11:20:16
...
主界面布局
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout 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:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.bwie.tablayoutdemo.MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<android.support.design.widget.TabLayout
android:id="@+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabIndicatorColor="@color/colorPrimary"
app:tabMode="scrollable"
app:tabSelectedTextColor="@color/red"
app:tabTextAppearance="@android:style/TextAppearance.Holo.Small"
app:tabIndicatorHeight="0dp"
app:tabContentStart="5dp"
app:textAllCaps="true"
app:tabTextColor="@color/black" />
<android.support.v4.view.ViewPager
android:id="@+id/vp_view"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#fff"
android:id="@+id/lvLeft"
/>
</android.support.v4.widget.DrawerLayout>
Pager_item
<?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">
<com.handmark.pulltorefresh.library.PullToRefreshListView
xmlns:ptr="http://schemas.android.com/apk/res-auto"
android:id="@+id/pull_refresh_list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:cacheColorHint="#000000"
android:divider="#19000000"
android:dividerHeight="4dp"
android:fadingEdge="none"
android:fastScrollEnabled="false"
android:footerDividersEnabled="false"
android:headerDividersEnabled="false"
android:smoothScrollbar="true"
ptr:ptrAnimationStyle="rotate"
ptr:ptrHeaderTextColor="#ffffff"
ptr:ptrHeaderSubTextColor="#00ffff"
ptr:ptrHeaderBackground="@null"
ptr:ptrDrawable="@mipmap/ic_launcher"/>
</LinearLayout>
list_item0
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:text="TextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textView"
android:layout_marginLeft="10dp"
/>
</LinearLayout>
list_item1
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_marginLeft="5dp"
app:srcCompat="@mipmap/ic_launcher"
android:id="@+id/imageView"
/>
<TextView
android:text="TextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textView"
android:layout_marginLeft="10dp"
/>
</LinearLayout>
主界面代码
package com.bwie.tablayoutdemo;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import com.bwie.myFragments.ChannelFragment;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private TabLayout mTablayout;
private ViewPager mViewPager;
private ListView lvLeft;
private DrawerLayout drawerLayout;
private String[] menu = {"收藏","设置","钱包","反馈"};
private String[] channels = {"推荐","热点","体育","娱乐","社会","汽车","教育","财经","科技","游戏"};
private String[] urlS = {
"http://gank.io/api/data/Android/10/1",
"http://gank.io/api/data/iOS/10/1",
"http://gank.io/api/data/%E7%A6%8F%E5%88%A9/10/1",
"http://gank.io/api/data/%E7%A6%8F%E5%88%A9/10/1",
"http://gank.io/api/data/%E7%A6%8F%E5%88%A9/10/1",
"http://gank.io/api/data/%E7%A6%8F%E5%88%A9/10/1",
"http://gank.io/api/data/%E7%A6%8F%E5%88%A9/10/1",
"http://gank.io/api/data/%E7%A6%8F%E5%88%A9/10/1",
"http://gank.io/api/data/%E7%A6%8F%E5%88%A9/10/1",
"http://gank.io/api/data/%E7%A6%8F%E5%88%A9/10/1"
};
private List<String> mTitleList = new ArrayList<>();//页卡标题集合
// private ChannelFragment view1, view2, view3, view4, view5,view6, view7, view8, view9, view10;//页卡视图
private List<ChannelFragment> mViewList = new ArrayList<>();//页卡视图集合
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
drawerLayout = (DrawerLayout) findViewById(R.id.activity_main);
mViewPager = (ViewPager) findViewById(R.id.vp_view);
mTablayout = (TabLayout) findViewById(R.id.tabs);
lvLeft = (ListView) findViewById(R.id.lvLeft);
for(int i=0;i<channels.length;i++){
//创建栏目的fragment
ChannelFragment fragment = new ChannelFragment();
Bundle b = new Bundle();
b.putString("name", channels[i]);//传递名字
b.putString("url", urlS[i]);
fragment.setArguments(b);
//收集fragment
mViewList.add(fragment);
//给tablayout添加tab选项卡
mTablayout.addTab(mTablayout.newTab().setText(channels[i]));//添加tab选项卡
}
FragmentManager fm = getSupportFragmentManager();
MyFragmentPagerAdapter mAdapter = new MyFragmentPagerAdapter(fm, mViewList);
mViewPager.setAdapter(mAdapter);//给ViewPager设fsf置适配器
mTablayout.setupWithViewPager(mViewPager);//将TabLayout和ViewPager关联起来。
mTablayout.setTabsFromPagerAdapter(mAdapter);//给Tabs设置适配器
// int count = mTablayout.getTabCount();
//
// for (int j=0;j<count;j++){
// TabLayout.Tab tab= mTablayout.getTabAt(j);
// tab.setIcon(R.mipmap.ic_launcher);
// }
// mTablayout.addTab(mTablayout.newTab().setText(channels[0]).setIcon(R.mipmap.ic_launcher));
// mTablayout.getTabAt(3).select();
//给侧滑中的listview配置数据
initDataForListViewLeft();
}
private void initDataForListViewLeft() {
//
ArrayAdapter<String> lvLeftAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,menu);
lvLeft.setAdapter(lvLeftAdapter);
//添加监听
lvLeft.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(MainActivity.this,menu[position],Toast.LENGTH_SHORT).show();
drawerLayout.closeDrawer(lvLeft);
//做相关的业务,,比如:让viewpager联动滑动到对应的pager
// mViewPager.setCurrentItem(position);
}
});
}
class MyFragmentPagerAdapter extends FragmentPagerAdapter{
private List<ChannelFragment> mViewList;
public MyFragmentPagerAdapter(FragmentManager fm, List<ChannelFragment> mViewList) {
super(fm);
this.mViewList = mViewList;
}
@Override
public Fragment getItem(int position) {
return mViewList.get(position);
}
@Override
public int getCount() {
return mViewList.size();
}
@Override
public String getPageTitle(int position) {
return channels[position];
}
}
// //ViewPager适配器
// class MyPagerAdapter extends PagerAdapter {
// private List<ChannelFragment> mViewList;
//
// public MyPagerAdapter(List<ChannelFragment> mViewList) {
// this.mViewList = mViewList;
// }
//
// @Override
// public int getCount() {
// return mViewList.size();//页卡数
// }
//
// @Override
// public boolean isViewFromObject(View view, Object object) {
// return view == object;//官方推荐写法
// }
//
// @Override
// public Object instantiateItem(ViewGroup container, int position) {
// container.addView(mViewList.get(position));//添加页卡
// return mViewList.get(position);
// }
//
// @Override
// public void destroyItem(ViewGroup container, int position, Object object) {
// container.removeView(mViewList.get(position));//删除页卡
// }
//
// @Override
// public CharSequence getPageTitle(int position) {
// return mTitleList.get(position);//页卡标题
// }
//
// }
}
ChannelFragment
package com.bwie.myFragments;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import com.bwei.beans.Result;
import com.bwei.beans.SuperClass;
import com.bwei.utils.NetWorkUtils;
import com.bwie.adapters.MyPullToListViewAdapter;
import com.bwie.tablayoutdemo.R;
import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import java.util.ArrayList;
/**
* Created by Administrator on 2017/9/14.
*/
public class ChannelFragment extends Fragment{
private String name;
private String news_url;
private PullToRefreshListView pullToRefreshListView;
private MyPullToListViewAdapter adapter;
private ArrayList<Result> results;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = getArguments();
name = (String) bundle.get("name");
news_url = (String) bundle.get("url");
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.pager_item, null);
pullToRefreshListView = (PullToRefreshListView) view.findViewById(R.id.pull_refresh_list);
//刚进来,网络请求数据,配置数据
refreshData();
//配置刷新,加载
pullToRefreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
@Override
public void onRefresh(PullToRefreshBase<ListView> refreshView) {
refreshData();
}
});
pullToRefreshListView.setOnLastItemVisibleListener(new PullToRefreshBase.OnLastItemVisibleListener() {
@Override
public void onLastItemVisible() {
loadMoreDate();
}
});
return view;
}
public void refreshData(){
new AsyncTask<String,Integer,String>(){
@Override
protected String doInBackground(String... params) {
String json = new NetWorkUtils().getJsonByUrlConnection(news_url);
return json;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
//解析json
SuperClass superClass = new Gson().fromJson(s, SuperClass.class);
results = superClass.getResults();
adapter = new MyPullToListViewAdapter(getActivity(), results);
pullToRefreshListView.setAdapter(adapter);
pullToRefreshListView.onRefreshComplete();
}
}.execute();
}
public void loadMoreDate(){
new AsyncTask<String,Integer,String>(){
@Override
protected String doInBackground(String... params) {
String json = new NetWorkUtils().getJsonByUrlConnection(news_url);
return json;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
//解析json
SuperClass superClass = new Gson().fromJson(s, SuperClass.class);
results.addAll(superClass.getResults());
adapter.notifyDataSetChanged();
}
}.execute();
}
}
工具类
package com.bwei.utils;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
* Created by Administrator on 2017/9/7.
*/
public class NetWorkUtils {
public String getJsonByUrlConnection(String jsonUrl){
String str = "";
try {
URL url = new URL(jsonUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
int resCode = conn.getResponseCode();
if(resCode == 200){
InputStream is = conn.getInputStream();
byte[] b = new byte[1024];
int len = 0;
while((len=is.read(b)) != -1){
str += new String(b,0,len);
}
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return str;
}
}
适配器
package com.bwie.adapters;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.bwei.beans.Result;
import com.bwie.tablayoutdemo.R;
import com.nostra13.universalimageloader.core.ImageLoader;
import java.util.ArrayList;
/**
* Created by Administrator on 2017/9/20.
*/
public class MyPullToListViewAdapter extends BaseAdapter {
private Context context;
private ArrayList<Result> results;
public MyPullToListViewAdapter(Context context, ArrayList<Result> results) {
this.context = context;
this.results = results;
}
@Override
public int getCount() {
return results.size();
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
//多条目配置
@Override
public int getViewTypeCount() {
return 2;
}
@Override
public int getItemViewType(int position) {
Result result = results.get(position);
if(result.getUrl() !="" && result.getUrl()!= null){//有图片,用有图片的布局
return 1;
}else{//没有图片,用没有图片的布局
return 0;
}
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder0 holder0;
ViewHolder1 holder1;
int i = getItemViewType(position);
if(i==0){
if(convertView == null){
holder0 = new ViewHolder0();
convertView = View.inflate(context, R.layout.list_item0,null);
holder0.who = (TextView) convertView.findViewById(R.id.textView);
convertView.setTag(holder0);
}else{
holder0 = (ViewHolder0) convertView.getTag();
}
Result r = results.get(position);
holder0.who.setText(r.getWho());
}else if(i==1){
if(convertView == null){
holder1 = new ViewHolder1();
convertView = View.inflate(context, R.layout.list_item1,null);
holder1.who = (TextView) convertView.findViewById(R.id.textView);
holder1.img = (ImageView) convertView.findViewById(R.id.imageView);
convertView.setTag(holder1);
}else{
holder1 = (ViewHolder1) convertView.getTag();
}
Result r = results.get(position);
holder1.who.setText(r.getWho());
ImageLoader.getInstance().displayImage(r.getUrl(), holder1.img);
}
return convertView;
}
class ViewHolder0{
TextView who;
}
class ViewHolder1{
TextView who;
ImageView img;
}
}
Myapp
package com.bwei.myapp;
import android.app.Application;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
/**
* Created by Administrator on 2017/9/20.
*/
public class MyApp extends Application {
@Override
public void onCreate() {
super.onCreate();
//imageloader初始化
ImageLoaderConfiguration configuration = ImageLoaderConfiguration.createDefault(this);
ImageLoader.getInstance().init(configuration);
}
}
Bean
package com.bwei.beans;
import java.util.ArrayList;
/**
* Created by Administrator on 2017/9/20.
*/
public class SuperClass {
private String error;
private ArrayList<Result> results;
public SuperClass(ArrayList<Result> results, String error) {
this.results = results;
this.error = error;
}
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
public ArrayList<Result> getResults() {
return results;
}
public void setResults(ArrayList<Result> results) {
this.results = results;
}
@Override
public String toString() {
return "SuperClass{" +
"error='" + error + '\'' +
", results=" + results +
'}';
}
}
Bean2
package com.bwei.beans;
/**
* Created by Administrator on 2017/9/20.
*/
public class Result {
private String desc;
private String publishedAt;
private String url;
private String who;
public Result(String desc, String publishedAt, String url, String who) {
this.desc = desc;
this.publishedAt = publishedAt;
this.url = url;
this.who = who;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getPublishedAt() {
return publishedAt;
}
public void setPublishedAt(String publishedAt) {
this.publishedAt = publishedAt;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getWho() {
return who;
}
public void setWho(String who) {
this.who = who;
}
@Override
public String toString() {
return "Result{" +
"desc='" + desc + '\'' +
", publishedAt='" + publishedAt + '\'' +
", url='" + url + '\'' +
", who='" + who + '\'' +
'}';
}
}
上一篇: IndexError: invalid index of a 0-dim tensor. Use tensor.item() to convert a 0-dim tensor to a Python
下一篇: js和原生应用常用的数据交互方式
推荐阅读
-
Pulltorefresh上拉加载下拉刷新
-
mui 上拉刷新下拉加载 pullToRefresh
-
3年以上勿进!最简单的Android自定义ListView下拉刷新与上拉加载,代码直接拿去用~
-
Android:下拉刷新+加载更多+滑动删除实例讲解
-
Android:下拉刷新+加载更多+滑动删除实例讲解
-
Android实现上拉加载更多ListView(PulmListView)
-
Android RecyclerView 上拉加载更多及下拉刷新功能的实现方法
-
ListView实现下拉刷新加载更多的实例代码(直接拿来用)
-
Android开源项目PullToRefresh下拉刷新功能详解
-
Android下拉刷新控件PullToRefresh实例解析