天天看點

PullToRefreshListView+Tablayout+Fragment+DrawerLayout

主布局
<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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.bawei.text06.MainActivity">
<LinearLayout
    android:background="#357"
    android:layout_width="300dp"
    android:layout_height="match_parent"
    android:layout_gravity="left"
    android:orientation="vertical">
    <ImageView
        android:id="@+id/img"
        android:background="@drawable/a"
        android:layout_gravity="center_horizontal"
        android:layout_width="115dp"
        android:layout_height="205dp" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_height="wrap_content"
        android:text="未登入"
        android:textSize="18sp" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_height="wrap_content"
        android:layout_marginTop="30dp"
        android:text="1"
        android:textSize="25sp" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_height="wrap_content"
        android:layout_marginTop="30dp"
        android:text="2"
        android:textSize="18sp" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_height="wrap_content"
        android:layout_marginTop="30dp"
        android:text="3"
        android:textSize="18sp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="30dp"
        android:text="4"
        android:textSize="18sp" />
</LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
        <FrameLayout
            android:id="@+id/fram"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:layout_above="@id/rg"></FrameLayout>
        <RadioGroup
            android:id="@+id/rg"
            android:layout_width="match_parent"
            android:layout_height="20dp"
            android:layout_alignParentBottom="true"
            android:orientation="horizontal">

            <RadioButton
                android:id="@+id/a"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:button="@null"
                android:checked="true"
                android:gravity="center"
                android:text="首頁" />

            <RadioButton
                android:id="@+id/b"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:button="@null"
                android:gravity="center"
                android:text="西瓜視訊" />

            <RadioButton
                android:id="@+id/c"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:button="@null"
                android:gravity="center"
                android:text="微頭條" />

            <RadioButton
                android:id="@+id/d"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:button="@null"
                android:gravity="center"
                android:text="我的" />

        </RadioGroup>


    </LinearLayout>
</android.support.v4.widget.DrawerLayout>
           
MainActivity
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.widget.RadioGroup;

import com.bawei.text06.fragment.AF;
import com.bawei.text06.fragment.BF;
import com.bawei.text06.fragment.CF;
import com.bawei.text06.fragment.DF;

public class MainActivity extends AppCompatActivity {

    private RadioGroup rg;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //查找控件
        rg = findViewById(R.id.rg);
        rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                switch (i){
                    case R.id.a:addFragment(new AF());
                    case R.id.b:addFragment(new BF());
                    case R.id.c:addFragment(new CF());
                    case R.id.d:addFragment(new DF());
                }
            }
        });
        addFragment(new AF());
    }

    private void addFragment(Fragment fragment) {
        getSupportFragmentManager().beginTransaction().replace(R.id.fram, fragment).commit();
    }
}
           
A、B、C、D布局 a.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical">

    <android.support.design.widget.TabLayout
        android:id="@+id/tab"
        app:tabIndicatorColor="@color/colorPrimary"
        app:tabSelectedTextColor="@color/colorPrimary"
        app:tabTextColor="@color/colorAccent"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <android.support.v4.view.ViewPager
        android:id="@+id/vp"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"></android.support.v4.view.ViewPager>
</LinearLayout>
           
A、B、C、D頁面
import android.os.Bundle;
import android.support.annotation.Nullable;
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.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.bawei.text06.R;
import com.bawei.text06.fragments.f1;
import com.bawei.text06.fragments.f2;
import com.bawei.text06.fragments.f3;
import com.bawei.text06.fragments.f4;
import com.bawei.text06.fragments.f5;
import com.bawei.text06.fragments.f6;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by sky on 2017/11/21.
 */

public class AF extends Fragment {
    private ViewPager vp;
    private TabLayout tab;
    List<String> tablist=new ArrayList<>();
    List<Fragment> fraglist=new ArrayList<>();

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = View.inflate(getActivity(), R.layout.a, null);
        //給TabLayout集合添加文字
        gettablist();
        //擷取fragment
        getfraglist();
        //通過ID擷取控件
        vp = v.findViewById(R.id.vp);
        tab = v.findViewById(R.id.tab);
        //設定TabLayout的模式
        tab.setTabMode(TabLayout.MODE_FIXED);
        //關聯ViewPager
        tab.setupWithViewPager(vp);
        //給ViewPager添加擴充卡
        MyvpAdaper m=new MyvpAdaper(getChildFragmentManager());
        vp.setAdapter(m);
        return v;
    }

    private void getfraglist() {
        fraglist.add(new f1());
        fraglist.add(new f2());
        fraglist.add(new f3());
        fraglist.add(new f4());
        fraglist.add(new f5());
        fraglist.add(new f6());
    }

    private void gettablist() {
        tablist.add("關注");
        tablist.add("推薦");
        tablist.add("十九大");
        tablist.add("熱點");
        tablist.add("科技");
        tablist.add("視訊");
    }

    private class MyvpAdaper extends FragmentPagerAdapter {
        public MyvpAdaper(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return fraglist.get(position);
        }

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

        //重寫傳回标題的方法
        @Override
        public CharSequence getPageTitle(int position) {
            return tablist.get(position);
        }
    }
}
           
f1、f2、f3、f4、f5布局 item.xml
<com.handmark.pulltorefresh.library.PullToRefreshListView
        android:id="@+id/pull"
        android:layout_width="match_parent"
        android:layout_height="match_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" />
           
顯示的頁面 item2.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">

    <ImageView
        android:id="@+id/img"
        android:layout_width="100dp"
        android:layout_height="100dp" />

    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>
           
f1、f2、f3、f4、f5頁面
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
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.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.bawei.text06.R;
import com.bawei.text06.bean.Bean;
import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.ILoadingLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;


/**
 * Created by sky on 2017/11/21.
 */

public class f1 extends Fragment {
    private String url = "http://www.meirixue.com/api.php?c=index&a=index";
    private PullToRefreshListView pullToRefreshListView;
    private StringBuilder builder;
    private List<Bean.DataBean.AdlistBean> list = new ArrayList<>();
    private Handler myHandler = new Handler();
    private MyAdapter adapter;
    int index = ;
    int type = ;

    @Nullable
    @Override

    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
       /* View inflate = inflater.inflate(R.layout.item, null);*/
        View v = View.inflate(getActivity(), R.layout.item, null);
        pullToRefreshListView = v.findViewById(R.id.pull);
        init();
        initLv();
        adapter = new MyAdapter();
        return v;
    }

    class Mytask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... strings) {
            try {
                //擷取url
                URL url = new URL(strings[]);
                //請求網絡
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                int code = urlConnection.getResponseCode();
                //判斷是否傳回成功
                if (code == ) {
                    //擷取網絡資訊
                    InputStream inputStream = urlConnection.getInputStream();
                    BufferedReader bf = new BufferedReader(new InputStreamReader(inputStream));
                    builder = new StringBuilder();
                    String s =null;
                    //拼接
                    while ((s = bf.readLine()) != null) {
                        builder.append(s);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }


            return builder.toString();
        }


        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            Gson gson = new Gson();
            Bean json = gson.fromJson(s, Bean.class);
            List<Bean.DataBean.AdlistBean> list1 = json.getData().getAdlist();
            //list.addAll(list1);
                list.addAll(list1);
            setAdapter();
            adapter.notifyDataSetChanged();
        }
    }

    public void setAdapter() {
            pullToRefreshListView.setAdapter(adapter);
    }

    public void init() {
        Mytask mytask = new Mytask();
        mytask.execute(url);

    }

    public void addtoTop() {
        type = ;
        index++;
        Mytask mytask = new Mytask();
        mytask.execute(url);

    }

    public void addtoBottom() {
        type = ;
        index++;
        Mytask mytask = new Mytask();
        mytask.execute(url);
    }

    public void initLv() {
        //設定重新整理模式 ,both代表支援上拉和下拉,pull_from_end代表上拉,pull_from_start代表下拉
        pullToRefreshListView.setMode(PullToRefreshBase.Mode.BOTH);


        ILoadingLayout startLabels = pullToRefreshListView.getLoadingLayoutProxy(true, false);
        startLabels.setPullLabel("下拉重新整理");
        startLabels.setRefreshingLabel("正在拉");
        startLabels.setReleaseLabel("放開重新整理");

        ILoadingLayout endLabels = pullToRefreshListView.getLoadingLayoutProxy(false, true);
        endLabels.setPullLabel("上拉重新整理");
        endLabels.setRefreshingLabel("正在載入...");
        endLabels.setReleaseLabel("放開重新整理...");
        pullToRefreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {//下拉重新整理的回調
                //下拉重新整理的資料,顯示在listview清單的最上面
                addtoTop();
                myHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        //重新整理完成,必須在異步下完成
                        pullToRefreshListView.onRefreshComplete();
                        //重新整理擴充卡
                    }
                }, );
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {//上拉加載的回調
                //加載更多的資料,添加到集合清單的最後面
                addtoBottom();
                myHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        //重新整理完成,必須在異步下完成
                        pullToRefreshListView.onRefreshComplete();
                    }
                }, );
            }
        });


    }


    class MyAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return list.size();
        }


        @Override
        public Object getItem(int position) {
            return null;
        }


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


        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            Viewholder vh;
            if (convertView == null) {
                vh = new Viewholder();
                convertView = View.inflate(getActivity(), R.layout.item2, null);
                vh.img = (ImageView) convertView.findViewById(R.id.img);
                vh.tv = (TextView) convertView.findViewById(R.id.tv);
                convertView.setTag(vh);
            } else {
                vh = (Viewholder) convertView.getTag();
            }
            vh.tv.setText(list.get(position).getTitle());
            ImageLoader.getInstance().displayImage(list.get(position).getImg(), vh.img);
            return convertView;
        }
    }

    public static class Viewholder {
        ImageView img;
        TextView tv;
    }
}
           
ImageloaderUtil
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Environment;

import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;

import java.io.File;

/**
 * Created by sky on 2017/11/21.
 */

class ImageloaderUtil {
    public static void initConfig(Context context) {
            //配置
    //        File cacheFile=context.getExternalCacheDir();
            File cacheFile= new File(Environment.getExternalStorageDirectory()+"/"+"image");

            ImageLoaderConfiguration config=new ImageLoaderConfiguration.Builder(context)
                    .memoryCacheExtraOptions(, )//緩存圖檔最大的長和寬
                    .threadPoolSize()//線程池的數量
                    .threadPriority()
                    .memoryCacheSize(**)//設定記憶體緩存區大小
                    .diskCacheSize(**)//設定sd卡緩存區大小
                    .diskCache(new UnlimitedDiscCache(cacheFile))//自定義緩存目錄
                    .writeDebugLogs()//列印日志内容
                    .diskCacheFileNameGenerator(new Md5FileNameGenerator())//給緩存的檔案名進行md5加密處理
                    .build();

            ImageLoader.getInstance().init(config);

        }

        /**
         * 擷取圖檔設定類
         * @return
         */
        public static DisplayImageOptions getImageOptions(){

            DisplayImageOptions optionsoptions=new DisplayImageOptions.Builder()
                    .cacheInMemory(true)//使用記憶體緩存
                    .cacheOnDisk(true)//使用磁盤緩存
                    .bitmapConfig(Bitmap.Config.RGB_565)//設定圖檔格式
                    .displayer(new RoundedBitmapDisplayer())//設定圓角,參數代表弧度
                    .build();

            return optionsoptions;

        }
}
           
myapp
import android.app.Application;

/**
 * Created by sky on 2017/11/21.
 */

public class myapp extends Application {
    @Override
        public void onCreate() {
            super.onCreate();

            ImageloaderUtil.initConfig(this);
        }
}