Collection聚合了项目搭建的一些基本模块,节约开发者时间,协助项目的快速搭建,RecyclerView+Adapter+Retrofit+RxJava+MVP+DataManager+基本Base,可以知足一个项目的基本实现。java
github地址:github.com/usernameyan…
掘金地址:juejin.im/post/5ab998…
1.更新Realm数据库依赖。
2.更新RxJava、rxandroid、retrofit、converter-gson、adapter-rxjava2依赖。
3.封装好Fragment之间的交互,项目中能够选择使用一个Activity来做为跟容器,其它实现页面统一使用fragment来实现。
4.collectionLibary中的Config配置类增长json字段过滤、网络请求超时设置、网络请求头设置(全局请求头)。
5.增长自动换行布局。
6.Realm增长按数据字段查询和删除接口。
7.网络请求类型HttpType增长json类型请求参数。
8.网络请求增长个别接口请求头设置。
9.增长适配不一样手机像素。android
1.增长自定义控件TabLayout。git
1.RxJava的依赖更新。 2.修正RecyclerView头部布局不能铺满问题。 3.PopupWindow的使用。 4.DisplayUtils工具类对状态栏的修改。github
1.修正Retrofit DEFAULT_POST请求方式指向错误。 2.Retrofit 数据解析兼容没有公用been类,能够指定公用been类和不指定公用been类、或者混合使用。 3.Realm增长数据迁移(数据库字段增长或移除)。 4.增长几种通用的Dialog弹窗,提供方法自定义。 5.提供几种比较经常使用的Utils工具类数据库
1.增长DataManager用来统一管理数据请求,包括Retrofit的请求、SharePreference以及Realm的数据请求。
2.Retrofit的请求的整合。 3.PullToRefreshRecyclerView的空布局bug修改。json
1.框架的引入api
2.PullToRefreshRecyclerView的使用缓存
3.BaseRecyclerViewAdapter的使用微信
4.MVP+RxJava+Retrofit的封装使用网络
5.DataManager的使用
6.Base的使用
7.CustomView的使用
implementation 'com.youngman:collectionlibrary:1.2.8'
Error:Could not find com.android.support:appcompat-v7:27.x.x. 由于library的Support Repository是27.x.x,可能跟项目有所冲突,若是sdk已经装了27仍是会出现一样的错误。 解决办法:在项目根build.gradle中加入 maven { url "maven.google.com" }
<com.youngmanster.collectionlibrary.refreshrecyclerview.pulltorefresh.PullToRefreshRecyclerView
android:id="@+id/recycler_rv"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
复制代码
mRecyclerView.setPullRefreshEnabled(true);
mRecyclerView.setLoadMoreEnabled(true);
复制代码
mRecyclerView.setPullRefreshEnabled(true);
mRecyclerView.setLoadMoreEnabled(true);
mRecyclerView.setRefreshView(new DefinitionAnimationRefreshHeaderView(getActivity()));
mRecyclerView.setLoadMoreView(new DefinitionAnimationLoadMoreView(getActivity()));
复制代码
/***
* 下拉刷新分为4个状态
*/
//下拉的状态(还没到下拉到固定的高度时)
public static final int STATE_PULL_DOWN=0;//
//下拉到固定高度提示释放刷新的状态
public static final int STATE_RELEASE_REFRESH=1;
//刷新状态
public static final int STATE_REFRESHING=2;
//刷新完成
public static final int STATE_DONE=3;
复制代码
/***
* 加载更多分为3个状态
*/
//正在加载
public final static int STATE_LOADING = 0;
//加载完成
public final static int STATE_COMPLETE = 1;
//没有数据
public final static int STATE_NODATA= 2;
复制代码
#####自定义刷新的步骤:
在initView()作自定义布局、相关动画的初始化,最后在initView()方法的最后面添加如下代码便可。
//mContainer =LayoutInflater.from(context).inflate(R.layout.layout_default_arrow_refresh, null);
//把刷新头部的高度初始化为0
LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
lp.setMargins(0, 0, 0, 0);
this.setLayoutParams(lp);
this.setPadding(0, 0, 0, 0);
addView(mContainer, new LayoutParams(LayoutParams.MATCH_PARENT, 0));//把刷新布局添加进去
setGravity(Gravity.BOTTOM);
//测量高度
measure(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT);
mMeasuredHeight = getMeasuredHeight();
复制代码
setRefreshTimeVisible(boolean show)是用来设置是否显示刷新时间控件,在默认刷新样式中经过mRecyclerView.setRefreshTimeVisible(false)便可隐藏刷新时间,若是在自定义的布局中没有这项这个方法就能够忽略。
destroy()是用来关掉改页面时把刷新View的一些动画等释放,防止内存泄漏。
在构造函数中
onStateChangeListener=this;
复制代码
onStateChange的模板样式
@Override
public void onStateChange(int state) {
//下拉时状态相同不作继续保持原有的状态
if (state == mState) return ;
//根据状态进行动画显示
switch (state){
case STATE_PULL_DOWN://跟随手指下拉的状态
//clearAnim();
//startAnim();
break;
case STATE_RELEASE_REFRESH://下拉释放
break;
case STATE_REFRESHING://正在进行刷新
//clearAnim();
//startAnim();
scrollTo(mMeasuredHeight);//这段代码须要添加
break;
case STATE_DONE://刷新完成
break;
}
mState = state;//状态的更新
}
复制代码
在initView()作自定义布局、相关动画的初始化,最后在initView()方法的最后面添加如下代码便可。
//mContainer = LayoutInflater.from(context).inflate(R.layout.layout_definition_animation_loading_more, null);
addView(mContainer);
setGravity(Gravity.CENTER);
复制代码
destroy()是用来关掉改页面时把刷新View的一些动画等释放,防止内存泄漏。
在setState()进行状态切换后的相关操做逻辑,模板样式:
@Override
public void setState(int state) {
switch (state){
case STATE_LOADING://正在加载
//loadMore_Ll.setVisibility(VISIBLE);
//noDataTv.setVisibility(INVISIBLE);
//animationDrawable= (AnimationDrawable) loadingIv.getDrawable();
//animationDrawable.start();
this.setVisibility(VISIBLE);//这段代码须要添加
break;
case STATE_COMPLETE:
//if(animationDrawable!=null){
// animationDrawable.stop();
//}
this.setVisibility(GONE);//这段代码须要添加
break;
case STATE_NODATA:
//loadMore_Ll.setVisibility(INVISIBLE);
//noDataTv.setVisibility(VISIBLE);
//animationDrawable= (AnimationDrawable) loadingIv.getDrawable();
//animationDrawable.start();
this.setVisibility(VISIBLE);//这段代码须要添加
break;
}
mState = state;//状态的更新
}
复制代码
<android.support.v4.widget.SwipeRefreshLayout
android:id="@+id/swipeRefreshLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.youngmanster.collectionlibrary.refreshrecyclerview.pulltorefresh.PullToRefreshRecyclerView
android:id="@+id/recycler_rv"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</android.support.v4.widget.SwipeRefreshLayout>
复制代码
mRecyclerView.setLoadMoreEnabled(true);
mRecyclerView.setLoadMoreView(new DefinitionAnimationLoadMoreView(getActivity()));
swl_Refresh.setColorSchemeResources(R.color.colorAccent);
swl_Refresh.setOnRefreshListener(this);
复制代码
因为PullToRefreshRecyclerView的下拉刷新和下拉加载更多完成时会自动刷新Adapter,而SwipeRefreshLayout刷新完成时须要手动进行notifyDataSetChanged刷新适配器。
View emptyView = LayoutInflater.from(getActivity()).inflate(R.layout.layout_empty,null);
mRecyclerView.setEmptyView(emptyView);
复制代码
mRecyclerView.setNoMoreDate(true);
复制代码
mRecyclerView.setAutoRefresh();
复制代码
mRecyclerView.isLoading() //是否正在加载更多
mRecyclerView.loadMoreComplete() //加载更多完成
mRecyclerView.isRefreshing() //是否正在刷新
mRecyclerView.refreshComplete(); //刷新数据完成
复制代码
onRecyclerViewRefresh()
onRecyclerViewLoadMore()
复制代码
//下拉刷新、上拉加载更多设置
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
refreshRv.setLayoutManager(linearLayoutManager);
refreshRv.setRefreshView(new DefinitionAnimationRefreshHeaderView(getActivity()));
refreshRv.setLoadMoreView(new DefinitionAnimationLoadMoreView(getActivity()));
refreshRv.setPullRefreshEnabled(true);
refreshRv.setLoadMoreEnabled(true);
refreshRv.setRefreshAndLoadMoreListener(this);
============================下面是下拉刷新上拉加载更多的一些操做=========================================
//刷新页面
@Override
public void refreshUI(List<WeChatNews> newsList) {
//先作数据拼接
if(newsList!=null){
if (pageSize == 1) {
mDatas.clear();
mDatas.addAll(newsList);
} else {
mDatas.addAll(newsList);
}
}
if (weChatFeaturedAdapter == null) {
//配合StateView使用,StateView具体使用下面有介绍
if(mDatas.size()==0){
stateView.showViewByState(StateView.STATE_EMPTY);
}else{
stateView.showViewByState(StateView.STATE_NO_DATA);
}
weChatFeaturedAdapter = new WeChatFeaturedAdapter(getActivity(), mDatas, refreshRv);
refreshRv.setAdapter(weChatFeaturedAdapter);
} else {
//判断该操做是下拉刷新仍是上拉加载更多
if (refreshRv.isLoading()) {
refreshRv.loadMoreComplete();
//若是没有更多数据就显示没有更多数据提示
if (newsList==null||newsList.size() == 0) {
refreshRv.setNoMoreDate(true);
}
} else if (refreshRv.isRefreshing()) {
refreshRv.refreshComplete();
}
}
}
复制代码
@Override
public void onDestroy() {
super.onDestroy();
if(mRecyclerView!=null){
mRecyclerView.destroy();
}
}
复制代码
在BaseRecyclerViewAdapter中的BaseViewHolder进行布局转化,同时定义了一些比较基本的View操做,使用简单。 #####(1)使用代码:
public class PullToRecyclerViewAdapter extends BaseRecyclerViewAdapter<String> {
public PullToRecyclerViewAdapter(Context mContext, List<String> mDatas, PullToRefreshRecyclerView pullToRefreshRecyclerView) {
super(mContext, R.layout.item_pull_refresh, mDatas, pullToRefreshRecyclerView);
}
@Override
protected void convert(BaseViewHolder baseViewHolder, String s) {
baseViewHolder.setText(R.id.title,s);
}
}
复制代码
public BaseRecyclerViewAdapter(Context mContext, int mLayoutResId, List<T> mDatas, PullToRefreshRecyclerView pullToRefreshRecyclerView) {
this.mContext = mContext;
this.mLayoutResId = mLayoutResId;
this.mDatas = mDatas;
this.mRecyclerView=pullToRefreshRecyclerView;
}
public BaseRecyclerViewAdapter(Context mContext, int mLayoutResId, List<T> mDatas) {
this.mContext = mContext;
this.mLayoutResId = mLayoutResId;
this.mDatas = mDatas;
}
复制代码
itemClickAdapter.setOnItemClickListener(new BaseRecyclerViewAdapter.OnItemClickListener() {
@Override
public void onItemClick(View view, int position) {
showToast(mDatas.get(position).getTitle());
}
});
复制代码
itemClickAdapter.setOnItemLongClickListener(new BaseRecyclerViewAdapter.onItemLongClickListener() {
@Override
public boolean onItemLongClick(View view, int position) {
showToast("进行长按操做");
return true;
}
});
复制代码
//事件监听
itemClickAdapter.setOnItemClickListener(this);
itemClickAdapter.setOnItemLongClickListener(this);
//点击实现
@Override
public void onItemClick(View view, int position) {
showToast(mDatas.get(position).getTitle());
}
@Override
public boolean onItemLongClick(View view, int position) {
showToast("进行长按操做");
return true;
}
复制代码
public class MultipleAdapter extends BaseRecyclerViewMultiItemAdapter<MultiItem> {
private int mHeight;
public MultipleAdapter(Context mContext, List<MultiItem> mDatas) {
super(mContext, mDatas);
mHeight = DisplayUtil.dip2px(mContext, 100);
addItemType(MultiItem.TYPE_TEXT, R.layout.item_main);
addItemType(MultiItem.TYPE_IMG, R.layout.item_img);
addItemType(MultiItem.TYPE_TEXT_IMG, R.layout.item_click);
}
@Override
protected void convert(BaseViewHolder baseViewHolder, MultiItem multiItem) {
switch (baseViewHolder.getItemViewType()) {
case MultiItem.TYPE_TEXT:
baseViewHolder.getView(R.id.card_view).getLayoutParams().height = mHeight;
baseViewHolder.setText(R.id.title, multiItem.getTitle());
break;
case MultiItem.TYPE_IMG:
baseViewHolder.setImageResource(R.id.ivImg, multiItem.getRes());
break;
case MultiItem.TYPE_TEXT_IMG:
baseViewHolder.setImageResource(R.id.ivImg, multiItem.getRes());
baseViewHolder.setText(R.id.titleTv, multiItem.getTitle());
break;
}
}
复制代码
ItemTouchHelper.Callback callback=new BaseRecycleItemTouchHelper(dragAndDeleteAdapter);
ItemTouchHelper itemTouchHelper=new ItemTouchHelper(callback);
itemTouchHelper.attachToRecyclerView(mRecyclerView);
复制代码
@Override
public void onDragAndDeleteFinished() {
mRecyclerView.postDelayed(new Runnable() {
@Override
public void run() {
dragAndDeleteAdapter.notifyDataSetChanged();
showToast("操做完成");
}
},300);
}
复制代码
public class Config {
/**必传参数**/
//是否为BuildConfig.DEBUG,日志输出须要
public static boolean DEBUG;
//设置Context
public static Context CONTEXT;
/**Retrofit**/
//网络请求的域名
public static String URL_DOMAIN;
//网络缓存地址
public static String URL_CACHE;
//设置OkHttp的缓存机制的最大缓存时间,默认为一天
public static long MAX_CACHE_SECONDS= 60 * 60 * 24;
//缓存最大的内存,默认为10M
public static long MAX_MEMORY_SIZE=10 * 1024 * 1024;
//设置该参数能够去掉json某个字段不解析,好比EXPOSEPARAM=“data”,json的data字段内容不被解析
public static String EXPOSEPARAM;
//设置网络请求json通用解析类
public static Class MClASS;
/**SharePreference**/
public static String USER_CONFIG;
/**Realm**/
public static RealmMigration realmMigration;
public static int realmVersion=0;
public static String realmName="myRealm.realm";
/***请求接口超时设定**/
public static int CONNECT_TIMEOUT_SECONDS=60;
public static int READ_TIMEOUT_SECONDS=60;
public static int WRITE_TIMEOUT_SECONDS=60;
/***设置全局请求头***/
public static Map<String,String> HEADERS;
}
复制代码
private void config(){
Config.DEBUG= BuildConfig.DEBUG;//这个若是是测试时,日志输出,网络请求相关信息输出
Config.URL_CACHE=AppConfig.URL_CACHE;//OkHttp缓存地址
Config.CONTEXT=this;//这个是必传
Config.MClASS= Result.class;//若是项目的json数据格式统一能够设置一个统一的been类
Config.URL_DOMAIN="http://api.tianapi.com/";//网络请求域名
}
复制代码
public class Result<T> implements Serializable {
private int code;
private String msg;
private T newslist;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public T getNewslist() {
return newslist;
}
public void setNewslist(T newslist) {
this.newslist = newslist;
}
}
复制代码
public class WeChatWorldNewsPresenter extends WeChatWorldNewsContract.Presenter {
@Override
public void requestWorldNews(int page, int num) {
RequestBuilder<Result<List<WeChatNews>>> resultRequestBuilder = new RequestBuilder<>(new RxObservableListener<Result<List<WeChatNews>>>(mView) {
@Override
public void onNext(Result<List<WeChatNews>> result) {
mView.refreshUI(result.getNewslist());
}
});
resultRequestBuilder
.setUrl(ApiUrl.URL_WETCHAT_WORLD_NEWS)
.setTransformClass(WeChatNews.class)
.setRequestParam(ApiClient.getRequiredBaseParam())
.setHttpTypeAndReqType(RequestBuilder.HttpType.DEFAULT_GET, RequestBuilder.ReqType.DEFAULT_CACHE_LIST)
.setParam("page",page)
.setParam("num",num);
rxManager.addObserver(DataManager.getInstance(DataManager.DataType.RETROFIT).httpRequest(resultRequestBuilder));
}
}
复制代码
public class WeChatChinaNewsDefinitionPresenter extends WeChatChinaNewsContract.Presenter {
@Override
public void requestChinaNews(int page, int num) {
String filePath = AppConfig.STORAGE_DIR + "wechat/china";
String fileName = "limttime.t";
RequestBuilder resultRequestBuilder = new RequestBuilder<>(new RxObservableListener<Result<List<WeChatNews>>>(mView) {
@Override
public void onNext(Result<List<WeChatNews>> result) {
mView.refreshUI(result.getNewslist());
}
}).setFilePathAndFileName(filePath, fileName)
.setTransformClass(WeChatNews.class)
.setUrl(ApiUrl.URL_WETCHAT_CHINA_NEWS)
.setRequestParam(ApiClient.getRequiredBaseParam())
.setHttpTypeAndReqType(RequestBuilder.HttpType.DEFAULT_GET,RequestBuilder.ReqType.DISK_CACHE_LIST_LIMIT_TIME)
.setParam("page", page)
.setParam("num", num);
rxManager.addObserver(DataManager.getInstance(DataManager.DataType.RETROFIT).httpRequest(resultRequestBuilder));
}
}
复制代码
resultRequestBuilder.setUrl(ApiUrl.URL_ABOUT_US_RULE)
.setTransformClass(ContractUsInfo.class)
.setParam("code","contact_us")
.setHeader("Accept-Language",MultiLanguageUtils.getInstance().getRequestLanguage())
.setHttpTypeAndReqType(RequestBuilder.HttpType.JSON_PARAM_POST, RequestBuilder.ReqType.NO_CACHE_MODEL);
rxManager.addObserver(DataManager.getInstance(DataManager.DataType.RETROFIT).httpRequest(resultRequestBuilder));
复制代码
void onNext(T result);
void onComplete();
void onError(NetWorkCodeException.ResponseThrowable e);
复制代码
protected RxObservableListener(BaseView view){
this.mView = view;
}
protected RxObservableListener(BaseView view, String errorMsg){
this.mView = view;
this.mErrorMsg = errorMsg;
}
复制代码
提供了三种方式
public enum DataType {
RETROFIT, REALM, SHAREPREFERENCE
}
复制代码
经过DataManager.getInstance(DataManager.DataType.XXX)可得到对应的请求方式。
须要在项目的Application初始化Retrofit的一些参数
//基本配置
Config.DEBUG= BuildConfig.DEBUG;
Config.CONTEXT=this;
//Retrofit配置
Config.URL_CACHE=AppConfig.URL_CACHE;
Config.MClASS= Result.class;//若是项目的json数据格式统一能够设置一个统一的been类
Config.URL_DOMAIN="http://api.tianapi.com/";
复制代码
RequestBuilder<Result<List<WeChatNews>>> resultRequestBuilder = new RequestBuilder<>(new RxObservableListener<Result<List<WeChatNews>>>(mView) {
@Override
public void onNext(Result<List<WeChatNews>> result) {
mView.refreshUI(result.getNewslist());
}
});
resultRequestBuilder
.setUrl(ApiUrl.URL_WETCHAT_FEATURED)
.setTransformClass(WeChatNews.class)
.setRequestParam(ApiClient.getRequiredBaseParam())
.setParam("page",page)
.setParam("num",num);
rxManager.addObserver(DataManager.getInstance(DataManager.DataType.RETROFIT).httpRequest(resultRequestBuilder));
复制代码
RequestBuilder<WeChatNewsResult> resultRequestBuilder = new RequestBuilder<>(new RxObservableListener<WeChatNewsResult>(mView) {
@Override
public void onNext(WeChatNewsResult result) {
mView.refreshUI(result.getNewslist());
}
});
resultRequestBuilder
.setUrl(ApiUrl.URL_WETCHAT_FEATURED)
.setTransformClass(WeChatNewsResult.class)
.setRequestParam(ApiClient.getRequiredBaseParam())
.setParam("page",page)
.setParam("num",num);
rxManager.addObserver(DataManager.getInstance(DataManager.DataType.RETROFIT).httpRequest(resultRequestBuilder));
复制代码
RequestBuilder<WeChatNewsResult> resultRequestBuilder = new RequestBuilder<>(new RxObservableListener<WeChatNewsResult>(mView) {
@Override
public void onNext(WeChatNewsResult result) {
mView.refreshUI(result.getNewslist());
}
});
resultRequestBuilder
.setUrl(ApiUrl.URL_WETCHAT_FEATURED)
.setTransformClass(WeChatNewsResult.class)
.setUserCommonClass(false)
.setRequestParam(ApiClient.getRequiredBaseParam())
.setParam("page",page)
.setParam("num",num);
rxManager.addObserver(DataManager.getInstance(DataManager.DataType.RETROFIT).httpRequest(resultRequestBuilder));
复制代码
public enum ReqType {
//没有缓存
NO_CACHE_MODEL,
No_CACHE_LIST,
//默认Retrofit缓存
DEFAULT_CACHE_MODEL,
DEFAULT_CACHE_LIST,
//自定义磁盘缓存,返回List
DISK_CACHE_LIST_LIMIT_TIME,
//自定义磁盘缓存,返回Model
DISK_CACHE_MODEL_LIMIT_TIME,
//自定义磁盘缓存,没有网络返回磁盘缓存,返回List
DISK_CACHE_NO_NETWORK_LIST,
//自定义磁盘缓存,没有网络返回磁盘缓存,返回Model
DISK_CACHE_NO_NETWORK_MODEL,
//保存网络数据到本地磁盘,能够设定网络请求是否返回数据
DISK_CACHE_NETWORK_SAVE_RETURN_MODEL,
DISK_CACHE_NETWORK_SAVE_RETURN_LIST,
}
复制代码
public enum HttpType {
//GET请求
DEFAULT_GET,
//POST请求
DEFAULT_POST,
//若是请求URL出现中文乱码,可选择这个
FIELDMAP_POST,
//json格式请求参数
JSON_PARAM_POST,
//上传一张图片
ONE_MULTIPART_POST
}
复制代码
RequestBuilder<Result<List<WeChatNews>>> resultRequestBuilder = new RequestBuilder<>(new RxObservableListener<Result<List<WeChatNews>>>(mView) {
@Override
public void onNext(Result<List<WeChatNews>> result) {
mView.refreshUI(result.getNewslist());
}
});
resultRequestBuilder
.setUrl(ApiUrl.URL_WETCHAT_WORLD_NEWS)
.setTransformClass(WeChatNews.class)
.setHttpTypeAndReqType(RequestBuilder.HttpType.DEFAULT_GET, RequestBuilder.ReqType.DEFAULT_CACHE_LIST)
.setRequestParam(ApiClient.getRequiredBaseParam())
.setParam("page",page)
.setParam("num",num);
复制代码
<T> DisposableObserver<ResponseBody> httpRequest(RequestBuilder<T> requestBuilder);
复制代码
Observable<WeChatAccessToken> observable = RetrofitManager.getNoCacheApiService(ApiService.class)
.getWeChatStr(ApiUrl.URL_WECHAT_HOST + ApiUrl.ACCESS_TOKEN, reqParams);
DisposableObserver<WeChatAccessToken> observer = observable
.compose(RxSchedulers.<WeChatAccessToken>io_main())
.subscribeWith(new RxSubscriber<WeChatAccessToken>() {
@Override
public void _onNext(WeChatAccessToken weChatAccessToken) {
getUserInfo(weChatAccessToken);
}
@Override
public void _onError(NetWorkCodeException.ResponseThrowable responseThrowable) {
showToast(R.string.wx_LoginResultEmpty);
hideLoadingDialog();
finish();
}
@Override
public void _onComplete() {
}
});
rxManager.addObserver(observer);
复制代码
public interface ApiService {
/**
* 微信精选
* @param url
* @param map
* @return
*/
@GET
Observable<Result<List<WeChatNews>>> getWeChatFeaturedNews(@Url String url, @QueryMap Map<String,Object> map);
}
复制代码
须要在项目的Application初始化SharePreference的一些参数
//SharePreference配置
Config.USER_CONFIG="Collection_User";
复制代码
DataManager.getInstance(DataManager.DataType.SHAREPREFERENCE).saveByKeyWithSP("user","这
String user=DataManager.getInstance(DataManager.DataType.SHAREPREFERENCE).queryByKeyWithSP("user",String.class);是一条测试的内容");
复制代码
//自定义保存的配置文件名、key
void saveByNameAndKeyWithSP(String name, String key, Object object);
//使用在Application配置的保存文件名
void saveByKeyWithSP(String key,Object object);
//查询保存在自定义的配置文件的内容
<T> T queryByNameAndKeyWithSP(String name, String key, Class<T> clazz);
//查询保存在Application设置的文件的内容
<T> T queryByKeyWithSP(String key, Class<T> clazz);
复制代码
//Realm的配置
Config.realmVersion=0;
Config.realmName="realm.realm";
Config.realmMigration=customMigration;//数据库数据迁移(been类字段增长移除)
复制代码
classpath "io.realm:realm-gradle-plugin:5.0.0"
复制代码
apply plugin: 'realm-android'
复制代码
DataManager.getInstance(DataManager.DataType.REALM).saveOrUpdateWithPKByRealm(user);
user= (User) DataManager.getInstance(DataManager.DataType.REALM).queryFirstByRealm(User.class);
复制代码
/**
* 保存操做
*/
void saveOrUpdateWithPKByRealm(final RealmObject bean);
void saveOrUpdateWithPKByRealm(final List<? extends RealmObject> beans);
void saveWithoutPKByRealm(final RealmObject bean);
void saveWithoutPKByRealm(final List<? extends RealmObject> beans);
/**
* 查询操做
*/
RealmObject queryFirstByRealm(Class<? extends RealmObject> clazz);
RealmObject queryAllWithFieldByRealm(Class<? extends RealmObject> clazz, String fieldName, String value);
RealmObject queryWithFieldByRealm(Class<? extends RealmObject> clazz, String fieldName, String value)
List<? extends RealmObject> queryAllByRealm(Class<? extends RealmObject> clazz);
List<? extends RealmObject> queryAllWithSortByRealm(Class<? extends RealmObject> clazz, String fieldName,Boolean isAscendOrDescend);
/**
* 修改操做
*/
void updateParamWithPKByRealm(Class<? extends RealmObject> clazz, String primaryKeyName, Object primaryKeyValue, String fieldName,Object newValue);
/**
* 删除操做
*/
void deleteFirstByRealm(Class<? extends RealmObject> clazz);
void deleteAllByRealm(Class<? extends RealmObject> clazz);
void deleteAllWithFieldByRealm(Class<? extends RealmObject> clazz, String fieldName, String value)
复制代码
随着app版本的迭代,数据库的字段可能会增长或者移除这时候就须要用到Realm提供的RealmMigration进行设置。
public class CustomMigration implements RealmMigration {
@Override
public void migrate(DynamicRealm realm, long oldVersion, long newVersion) {
RealmSchema schema = realm.getSchema();
for(int i = (int) (oldVersion+1);i<=newVersion;i++){
if (i == 1) {
RealmObjectSchema personSchema = schema.get("BleLabelInfo");
RealmObjectSchema multilanguageSchema = schema.create("MultiLanguage");
multilanguageSchema.addField("zhHk", String.class);
multilanguageSchema.addField("zhCn", String.class);
multilanguageSchema.addField("en", String.class);
personSchema
.addRealmObjectField("multilingualism", multilanguageSchema);
} else if (i == 2) {
RealmObjectSchema personSchema = schema.get("User");
personSchema
.addField("id", String.class);
RealmObjectSchema multilanguageSchema = schema.create("LabelRecord");
multilanguageSchema.addField("major_minor", String.class);
multilanguageSchema.addPrimaryKey("major_minor");
multilanguageSchema.addField("major", String.class);
multilanguageSchema.addField("minor", String.class);
multilanguageSchema.addField("timeMillis", long.class);
multilanguageSchema.addField("threshold",int.class);
}else if(i==3){
RealmObjectSchema personSchema = schema.get("User");
personSchema
.addField("authType", boolean.class);
}
}
}
}
复制代码
public interface WeChatChinaNewsContract {
interface View extends BaseView {
void refreshUI(List<WeChatNews> weChatNews);
}
abstract class Presenter extends BasePresenter<View> {
public abstract void requestChinaNews(int page,int num);
}
}
复制代码
public class WeChatChinaNewsPresenter extends WeChatChinaNewsContract.Presenter {
@Override
public void requestChinaNews(int page, int num) {
RequestBuilder resultRequestBuilder = new RequestBuilder<>(new RxObservableListener<Result<List<WeChatNews>>>(mView) {
@Override
public void onNext(Result<List<WeChatNews>> result) {
mView.refreshUI(result.getNewslist());
}
}).setUrl(ApiUrl.URL_WETCHAT_CHINA_NEWS)
.setTransformClass(WeChatNews.class)
.setRequestParam(ApiClient.getRequiredBaseParam())
.setParam("page", page)
.setParam("num", num);
rxManager.addObserver(DataManager.getInstance(DataManager.DataType.RETROFIT).httpRequest(resultRequestBuilder));
}
}
复制代码
public class FragmentChinaNews extends BaseFragment<WeChatChinaNewsModel,WeChatChinaNewsPresenter> implements WeChatChinaNewsContract.View{
@Override
public void init() {
}
@Override
public void requestData() {
((WeChatChinaNewsPresenter)mPresenter).requestChinaNews(pageSize,PAGE_SIZE);
}
@Override
public void refreshUI(List<WeChatNews> newsList) {
}
@Override
public void onError(String errorMsg) {
}
}
复制代码
IBaseActivity:主要提供了一个页面的基本方法、处理了MVP之间的关联、使用者能够直接继承该类使用、也能够继承该类实现扩展。
IBaseActivity<T extends BaseModel, E extends BasePresenter>已经进行MVP之间的传递和关联。
处理好页面销毁以后Observables 和 Subscribers的解绑。
getLayoutId()设置布局、init()数据初始化、requestData()请求数据,执行顺序已经在IBaseActivity作好处理。
能够继承IBaseActivity进行扩展。
public abstract class BaseActivity<T extends BaseModel,E extends BasePresenter> extends IBaseActivity{ private Unbinder unbinder;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
unbinder= ButterKnife.bind(this);
}
复制代码
}
@Override
public void requestData() {
((WeChatFeaturedPresenter) mPresenter).requestFeaturedNews(pageSize, PAGE_SIZE);
}
复制代码
IBaseFragment:主要提供一个页面的基本方法,处理了MVP之间的关联,该类已经加入了懒人加载的控制方式、使用者能够直接继承该类使用、也能够继承该类实现扩展。
IBaseFragment<T extends BaseModel,E extends BasePresenter>已经进行MVP之间的传递和关联。
处理好页面销毁以后Observables 和 Subscribers的解绑。
加入了懒人加载方式,只有页面显示才会调用requestData()请求数据,并只会调用一次。
getLayoutId()设置布局、init()数据初始化、requestData()请求数据,执行顺序已经在IBaseFragment作好处理。
能够继承IBaseFragment进行扩展。
public abstract class BaseFragment<T extends BaseModel,E extends BasePresenter> extends IBaseFragment {
private Unbinder unbinder;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
unbinder= ButterKnife.bind(this,mainView);
return mainView;
}
}
复制代码
@Override
public void requestData() {
((WeChatChinaNewsPresenter)mPresenter).requestChinaNews(pageSize,PAGE_SIZE);
}
复制代码
[站外图片上传中...(image-4c118c-1566984217649)]
//不显示
public static final int STATE_NO_DATA = 0;
//正在加载
public static final int STATE_LOADING = 1;
//空数据
public static final int STATE_EMPTY = 2;
//没有网络
public static final int STATE_DISCONNECT=3;
复制代码
<?xml version="1.0" encoding="utf-8"?>
<com.youngmanster.collectionlibrary.base.StateView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerInParent="true"
android:id="@+id/state_view">
</com.youngmanster.collectionlibrary.base.StateView >
复制代码
<include layout="@layout/layout_state"/>
复制代码
stateView.showViewByState(StateView.STATE_LOADING);
stateView.showViewByState(StateView.STATE_EMPTY);
stateView.showViewByState(StateView.STATE_NO_DATA);
stateView.showViewByState(StateView.STATE_DISCONNECT);
复制代码
app:emptyText=""//设置空数据的文字提示
app:emptyImage=""//设置空数据显示的图片
app:disConnectImage=""//设置无网络的显示图片
app:disConnectText=""//设置无网络的文字提示
app:loadingText=""//设置loading的文字提示
app:loadingViewAnimation=""//设置loading的动画文件,只是ImageView
app:tipTextColor=""//设置文字显示颜色
app:tipTextSize=""//设置文字的大小
复制代码
// 项目的必须权限,没有这些权限会影响项目的正常运行
private static final String[] PERMISSIONS = new String[]{
Manifest.permission.READ_SMS,
Manifest.permission.RECEIVE_WAP_PUSH,
};
复制代码
PermissionManager permissionManager=PermissionManager.with(this).
//必须权限
setNecessaryPermissions(PERMISSIONS);
//经过如下语句进行请求
permissionManager.requestPermissions();
复制代码
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == PermissionManager.PERMISSION_REQUEST_CODE) {//PERMISSION_REQUEST_CODE为请求权限的请求值
//有必须权限选择了禁止
if (permissionManager.getShouldShowRequestPermissionsCode() == PermissionManager.EXIST_NECESSARY_PERMISSIONS_PROHIBTED) {
showToast("能够在这里设置从新跳出权限请求提示框");
} //有必须权限选择了禁止不提醒
else if (permissionManager.getShouldShowRequestPermissionsCode() == PermissionManager.EXIST_NECESSARY_PERMISSIONS_PROHIBTED_NOT_REMIND) {
showToast("能够在这里弹出提示框提示去应用设置页开启权限");
permissionManager.startAppSettings();
}
}
}
复制代码
继承BasePopupWindow。
经过getPopupLayoutRes(R.layout.xxx)设置弹窗布局。
经过getPopupAnimationStyleRes(R.style.xxx)设置弹窗动画,不须要动画能够忽略不设置。
<style name="animation_scale" parent="android:Animation.Dialog">
<item name="android:windowEnterAnimation">@anim/scale_tip_in</item>
<item name="android:windowExitAnimation">@anim/scale_tip_out</item>
</style>
复制代码
若是须要显示遮层,在构造函数经过setShowMaskView(true)设置。
<com.youngmanster.collectionlibrary.customview.wraplayout.AutoLinefeedLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
//填充的内容
</com.youngmanster.collectionlibrary.customview.wraplayout.AutoLinefeedLayout>
复制代码
[站外图片上传中...(image-6d936c-1566984217649)]