例题: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 类
import android.app.Application;
import com.example.shenhuiran_1215.utils.ImageloaderUtil;
public class MyApp extends Application{
@Override
public void onCreate() {
super.onCreate();
ImageloaderUtil.initConfig(this);
}
}
====================================================
Result方法:(json解析类)
import java.util.List;
public class Result {
private HeaderBean header;
private List<DataBean> data;
public HeaderBean getHeader() {
return header;
}
public void setHeader(HeaderBean header) {
this.header = header;
}
public List<DataBean> getData() {
return data;
}
public void setData(List<DataBean> data) {
this.data = data;
}
public static class HeaderBean {
private int totalsize;
private int totalpage;
private String first;
private String last;
private String next;
public int getTotalsize() {
return totalsize;
}
public void setTotalsize(int totalsize) {
this.totalsize = totalsize;
}
public int getTotalpage() {
return totalpage;
}
public void setTotalpage(int totalpage) {
this.totalpage = totalpage;
}
public String getFirst() {
return first;
}
public void setFirst(String first) {
this.first = first;
}
public String getLast() {
return last;
}
public void setLast(String last) {
this.last = last;
}
public String getNext() {
return next;
}
public void setNext(String next) {
this.next = next;
}
}
public static class DataBean {
private String id;
private String title;
private String summary;
private String otime;
private String source;
private String img;
private String url;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getSummary() {
return summary;
}
public void setSummary(String summary) {
this.summary = summary;
}
public String getOtime() {
return otime;
}
public void setOtime(String otime) {
this.otime = otime;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getImg() {
return img;
}
public void setImg(String img) {
this.img = img;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
}
============================================================================
布局:
<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 >
--------------------------------------------------
@drawable/rg_bj
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@color/rg_selected" android:state_checked="true"></item>
<item android:drawable="@color/rg_default" android:state_checked="false"></item>
</selector>
---------------------------------------------------
@color/text_selector
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="@color/rg_txt_selected" android:state_checked="true"></item>
<item android:color="@color/rb_txt_default" android:state_checked="false"></item>
</selector>
==================================================
import android.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();
}
==========================================================
主要代码:
import android.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>
===============================================
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.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 类
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.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方法
}