仿今日头条TabLayout,侧滑,上拉加载下拉刷新

正文

今天给大家讲解一下TabLayout+deawableLayout实现自定义下拉刷新、上拉加载和侧滑删除效果。

首先写他的布局

主页面的布局  侧拉以及TabLayout 

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


//主布局类

 

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];
        }
    }
    
}

接下来的是多条目加载的

 

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;

 

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;
    }
}

紧跟着就是两个布局

布局一

<?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>
布局二

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


//实现上拉加载下拉刷新的视图

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

//控制刷新加载的类

 

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;


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();
    }
}

接下来就是几个工具类

网络请求的

 
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;
    }
}

ImageLoader的类

 

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);
    }
}

values里的color.xml 添加这两个

<color name="red">#F00</color>
<color name="black">#000</color>

tabLayout需要添加依赖

 

compile 'com.android.support:appcompat-v7:24.2.1'
testCompile 'junit:junit:4.12'
compile 'com.android.support:design:24.2.0'
compile project(':library')
compile 'com.google.code.gson:gson:2.8.1'
compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'


library也需要更改build.gradle的版本号





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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值