仿今日頭條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的版本號





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章