1. 程式人生 > >Fragment,側滑菜單,PullToRefresh上下拉加載

Fragment,側滑菜單,PullToRefresh上下拉加載

inf lib findview tip tle limit drawer mis activit

例題:Fragment,側滑菜單,PullToRefresh上下拉加載
技術分享圖片
右鍵工程>Open Module Settings>Dependencies>+號Library dependency>com.android.support:design:27.0.2

=============================================

libs文件夾下加入jar包(導包): gson 和 universal-image-loader

=======================================

build.gradle中加入依賴(加在最下面):

pull-to-refresh上下拉刷新控件 :compile ‘com.github.userswlwork:pull-to-refresh:1.0.0‘

Banner無限輪播:compile ‘com.youth.banner:banner:1.4.10‘

添加之後需要點擊右上角的 Sync Now 編譯一下

====================================

添加權限:

網絡請求權限:INTERNET
<uses-permission android:name="android.permission.INTERNET"/>
網絡判斷權限:ACCESS_NETWORK_STATE
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

<application/>在這個控件裏加入屬性:android:name=".MyApp"
========================================
MyApp  類
importandroid.app.Application;
import com.example.shenhuiran_1215.utils.ImageloaderUtil;
public class MyApp  extends Application{
    @Override
    public void onCreate() {
        super.onCreate();
        ImageloaderUtil.initConfig(this
); } }

====================================================

Result方法:
public class Result {
json解析類
}
============================================================================
布局:
<android.support.v4.widget.DrawerLayout
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"
tools:context="com.example.shenhuiran_1215.MainActivity">
    <RelativeLayout
android:layout_width="260dp"
android:layout_height="match_parent"
android:background="#f00"
android:layout_gravity="start">
        <ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@mipmap/ic_launcher"/>
    </RelativeLayout>
    <RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/rel_main">
        <RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:id="@+id/rg"
android:layout_alignParentBottom="true">
            <RadioButton
android:layout_width="0dp"
android:layout_height="40dp"
android:layout_weight="1"
android:gravity="center"
android:checked="true"
android:id="@+id/rb_index"
android:text="上天"
android:textSize="25sp"
android:background="@drawable/rg_bj"
android:textColor="@color/text_selector"
android:button="@null"/>
            <RadioButton
android:layout_width="0dp"
android:layout_height="40dp"
android:layout_weight="1"
android:gravity="center"
android:id="@+id/rb_my"
android:text="下地"
android:textSize="25sp"
android:background="@drawable/rg_bj"
android:textColor="@color/text_selector"
android:button="@null"/>
        </RadioGroup>
        <FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/frcontent"
android:layout_above="@id/rg"
>
        </FrameLayout>
    </RelativeLayout>
</android.support.v4.widget.DrawerLayout >
==================================================
BaseActivity 基類
importandroid.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;
//基類
public abstract class BaseActivity extends AppCompatActivity {
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //設置內容視圖
setContentView(getActivityLayout());
        initView();
        setListener();
        initData();
    }
    //得到activity的布局
public abstract int getActivityLayout();
    //初使化界面上的控件
public abstract void initView();
    //初使化頁面中要使用到的數據
public abstract void initData();
    //設置監聽事件
public abstract void setListener();
    //彈出提示
public void showTip(String  str){
        Toast.makeText(this,str,Toast.LENGTH_SHORT).show();
    }
}
==================================================
BaseFragment 基類
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;
public abstract class BaseFragment extends Fragment {
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
       //調用抽象方法,返回fragment的布局
return getFragmentView(inflater,container);
    }
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
        setListener();
        initData();
    }
    //得到fragment的視圖
public abstract View getFragmentView(LayoutInflater inflater,ViewGroup container);
    public abstract void initView();
    public abstract void initData();
    public abstract void setListener();
}
==========================================================
主要代碼:
importandroid.widget.RadioGroup;
import com.example.shenhuiran_1215.base.BaseActivity;
import com.example.shenhuiran_1215.fragments.IndexFragment;
import com.example.shenhuiran_1215.fragments.MyFragment;

public class MainActivity extends BaseActivity {
    private RadioGroup radioGroup;
    @Override
    public int getActivityLayout() {
        return R.layout.activity_main;
    }
    @Override
    public void initView() {
        radioGroup = findViewById(R.id.rg);
    }
    @Override
    public void initData() {
        //默認添加首頁fragment
getSupportFragmentManager().beginTransaction().replace(R.id.frcontent,new IndexFragment()).commit();
        //調用父類中的公共方法
showTip("haha");
    }
    @Override
    public void setListener() {
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                switch (i){
                    case R.id.rb_index:
                        getSupportFragmentManager().beginTransaction().replace(R.id.frcontent,new IndexFragment()).commit();
                        break;
                    case R.id.rb_my:
                        getSupportFragmentManager().beginTransaction().replace(R.id.frcontent,new MyFragment()).commit();
                        break;
                }
            }
        });
    }
}
==========================================
MyFragment 類
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 com.example.shenhuiran_1215.R;
public class MyFragment extends Fragment {
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
       View v=inflater.inflate(R.layout.my,container,false);
        return v;
    }
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }
}
----------------------------------------------------------
布局:隨便加個背景顏色
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#00f">
</android.support.constraint.ConstraintLayout>
==============================================
IndexFragment 類
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.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.shenhuiran_1215.R;
import com.example.shenhuiran_1215.TabModel;
import com.example.shenhuiran_1215.base.BaseFragment;
import java.util.ArrayList;
import java.util.List;
public class IndexFragment extends BaseFragment {
    private TabLayout tabLayout;
    private ViewPager viewPager;
    //存放所有標簽信息的集合列表
private List<TabModel> list;
    private View v;
    @Override
    public View getFragmentView(LayoutInflater inflater, ViewGroup container) {
        v = inflater.inflate(R.layout.index,container,false);
        return v;
    }
    @Override
    public void initView() {
        tabLayout = v.findViewById(R.id.mytab);
        viewPager = v.findViewById(R.id.vp);
    }
    @Override
    public void initData() {
        list=new ArrayList<>();
        list.add(new TabModel("北鬥","xbsjxw"));
        list.add(new TabModel("天樞","txs"));
        list.add(new TabModel("天璇","toutiao"));
        list.add(new TabModel("天璣","news/mobile/jbgg"));
        list.add(new TabModel("天權","news/mobile/mgxw"));
        list.add(new TabModel("玉衡","news/mobile/ggxw"));
        list.add(new TabModel("開陽","news/mobile/jjxw"));
        list.add(new TabModel("瑤光","news/mobile/lcxw"));
        //設置適配器
viewPager.setAdapter(new MyAdapter(getChildFragmentManager()));//註意:在子fragment中,使用。。getChildFragmentManager
        //tablayout與vp進行關聯
tabLayout.setupWithViewPager(viewPager);
        //一次性加載完
viewPager.setOffscreenPageLimit(list.size());
    }
    @Override
    public void setListener() {
    }
    class MyAdapter extends FragmentPagerAdapter{
        public MyAdapter(FragmentManager fm) {
            super(fm);
        }
        @Override
        public CharSequence getPageTitle(int position) {
            return list.get(position).getTitle();//返回title信息
}
        @Override
        public Fragment getItem(int position) {
            ContentFragment fragment=new ContentFragment();
            //傳遞type
Bundle bundle=new Bundle();
            bundle.putString("type",list.get(position).getType());
            fragment.setArguments(bundle);
            return fragment;
        }
        @Override
        public int getCount() {
            return list.size();
        }
    }
}
----------------------------------------------
布局:
<RelativeLayout
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.support.design.widget.TabLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabGravity="center"
app:tabIndicatorColor="@color/colorAccent"
app:tabMode="scrollable"
app:tabSelectedTextColor="@color/colorPrimaryDark"
app:tabTextColor="@color/colorPrimary"
android:id="@+id/mytab"></android.support.design.widget.TabLayout>
    <android.support.v4.view.ViewPager
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/vp"
android:layout_below="@+id/mytab"></android.support.v4.view.ViewPager>
</RelativeLayout>
===============================================
importandroid.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.shenhuiran_1215.R;
import com.example.shenhuiran_1215.bean.Result;
import com.example.shenhuiran_1215.utils.ImageloaderUtil;
import com.nostra13.universalimageloader.core.ImageLoader;
import java.util.List;
public class MyAdapter extends BaseAdapter {
    private Context context;
    private List<Result.DataBean> data;
    private final  int LEFT_IMAGE=0;
    private final  int RIGHT_IMAGE=1;
    public MyAdapter(Context context, List<Result.DataBean> data) {
        this.context = context;
        this.data = data;
    }
    @Override
    public int getCount() {
        return data.size();
    }
    @Override
    public int getViewTypeCount() {
        return 2;
    }
    @Override
    public int getItemViewType(int position) {
        if(position%2==0){
            return RIGHT_IMAGE;
        }else {
            return LEFT_IMAGE;
        }
    }
    @Override
    public Object getItem(int i) {
        return null;
    }
    @Override
    public long getItemId(int i) {
        return 0;
    }
    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        //根據下標得到類型
int itemType = getItemViewType(i);
        if(itemType==LEFT_IMAGE){
            ViewHolder holder;
            if(view==null){
                view=View.inflate(context, R.layout.item_left,null);
                holder=new ViewHolder();
                holder.imageView=view.findViewById(R.id.img);
                holder.textView=view.findViewById(R.id.tv);
                view.setTag(holder);
            }else {
                holder=(ViewHolder) view.getTag();
            }
            holder.textView.setText(data.get(i).getTitle());
            String imgurl=data.get(i).getImg();
            if(!"".equals(imgurl) && imgurl!=null){
                ImageLoader.getInstance().displayImage(imgurl,holder.imageView, ImageloaderUtil.getImageOptions());
            }
            return  view;
        }else {
            ViewHolder holder;
            if(view==null){
                view=View.inflate(context, R.layout.item_right,null);
                holder=new ViewHolder();
                holder.imageView=view.findViewById(R.id.img);
                holder.textView=view.findViewById(R.id.tv);
                view.setTag(holder);
            }else {
                holder=(ViewHolder) view.getTag();
            }
            holder.textView.setText(data.get(i).getTitle());
            String imgurl=data.get(i).getImg();
            if(!"".equals(imgurl) && imgurl!=null){
                ImageLoader.getInstance().displayImage(imgurl,holder.imageView, ImageloaderUtil.getImageOptions());
            }
            return  view;
        }
    }
    class ViewHolder{
        ImageView imageView;
        TextView textView;
    }
}
-------------------------------------------------
兩個布局:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
    <ImageView
android:layout_width="80dp"
android:layout_height="80dp"
android:src="@mipmap/ic_launcher"
android:id="@+id/img"/>
    <TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/tv"
android:layout_toRightOf="@+id/img"/>
</RelativeLayout>
---------------------------------------
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
    <ImageView
android:layout_width="80dp"
android:layout_height="80dp"
android:src="@mipmap/ic_launcher"
android:id="@+id/img"
android:layout_alignParentRight="true"/>
    <TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/tv"
android:layout_toLeftOf="@+id/img"/>
</RelativeLayout>
============================================================
ContentFragment 類
importandroid.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.example.shenhuiran_1215.R;
import com.example.shenhuiran_1215.adapter.MyAdapter;
import com.example.shenhuiran_1215.bean.Result;
import com.example.shenhuiran_1215.utils.MyTask;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
public class ContentFragment extends Fragment {
    private PullToRefreshListView plv;
    private String type="";
    private String preUrl="http://mnews.gw.com.cn/wap/data/news/";
    private int pageIndex=1;
    private String nextUrl;
    private String url;
    private MyAdapter adapter;
    private  List<Result.DataBean> data;
    private int operType=1;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v=inflater.inflate(R.layout.content,container,false);
        plv = v.findViewById(R.id.plv);
        data=new ArrayList<>();
        //接收參數
Bundle arguments = getArguments();
        if(arguments!=null){
           type=arguments.getString("type");
           //進行url地址的拼接
nextUrl="/page_"+pageIndex+".json";
           url=preUrl+type+nextUrl;
        }
        return v;
    }
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initPlv();
        requestNetData();
    }
    private void requestNetData() {
        //請求網絡數據
MyTask myTask=new MyTask(new MyTask.Icallbacks() {
            @Override
            public void updateUiByjson(String jsonstr) {
                List<Result> list=new ArrayList<>();
                //得到集合類型
Type t=new TypeToken<List<Result>>(){}.getType();
                Gson gson=new Gson();
                list=gson.fromJson(jsonstr,t);
                //取得顯示的數據
Result data1 = list.get(0);
                if(operType==1){
                    data.clear();
                }
                data.addAll(data1.getData());
                //創建適配器
setAdapter();
                plv.onRefreshComplete();
            }
        });
        myTask.execute(url);
    }
    public void setAdapter(){
        if(adapter==null){
            adapter=new MyAdapter(getActivity(),data);
            plv.setAdapter(adapter);
        }else {
            adapter.notifyDataSetChanged();
        }
    }
    //初使化
private void initPlv() {
        plv.setMode(PullToRefreshBase.Mode.BOTH);
        plv.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> pullToRefreshBase) {
                pageIndex=1;
                nextUrl="/page_"+pageIndex+".json";
                url=preUrl+type+nextUrl;
                operType=1;
                requestNetData();
            }
            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> pullToRefreshBase) {
                pageIndex++;
                nextUrl="/page_"+pageIndex+".json";
                url=preUrl+type+nextUrl;
                operType=2;
                requestNetData();
            }
        });
    }
}
-----------------------------------------
布局:
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent">
    <com.handmark.pulltorefresh.library.PullToRefreshListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/plv"></com.handmark.pulltorefresh.library.PullToRefreshListView>
</android.support.constraint.ConstraintLayout>
==============================================================
TabModel 封裝類
public class TabModel {
    private String title;
    private String type;
有參方法
get set方法
}

Fragment,側滑菜單,PullToRefresh上下拉加載