最近看了一下jetpack框架,学习了一下别人写的mvvm框架,自己编写了一套始和自己的框架来使用,新手初写,多多指教!
BaseActivity(添加了标题以及返回按钮,同时设置状态颜色,同时与databinding使用)
public abstract class BaseActivity <V extends ViewDataBinding,VM extends BaseViewModel> extends AppCompatActivity {
public V viewdatabing;
public VM viewmodel;
private int viewmodelid;
private LayoutTitleBinding titleBinding;
//用来添加title
public TitleClickProxy clickProxy;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initParm();
initTitle();
initEvent();
fullScreen(this);
}
//事件执行
protected abstract void initEvent();
//设置title标题名称
protected abstract String initTitleName();
//设置初始化viewmodelid
protected abstract int initViewModelId();
//设置databinding布局
protected abstract int initContentView();
//事件执行逻辑
protected abstract View initLayout();
//菜单按钮
protected abstract void onClickSearch();
//设置title名称
private void initTitle(){
titleBinding = DataBindingUtil.setContentView(this, R.layout.layout_title);
if(null != initTitleName()){
clickProxy = new TitleClickProxy();
clickProxy.setTitleName(initTitleName());
titleBinding.setProxy(clickProxy);
}else {
titleBinding.rlTitle.setVisibility(View.GONE);
}
titleBinding.rlViewgroup.addView(initLayout());
}
//初始化参数
private void initParm() {
viewdatabing = DataBindingUtil.setContentView(this,initContentView());
viewmodel = initViewModel();
viewmodelid = initViewModelId();
if (viewmodel == null) {
Class modelClass;
Type type = getClass().getGenericSuperclass();
if (type instanceof ParameterizedType) {
modelClass = (Class) ((ParameterizedType) type).getActualTypeArguments()[1];
} else {
//如果没有指定泛型参数,则默认使用BaseViewModel
modelClass = BaseViewModel.class;
}
viewmodel = (VM) createViewModel(this, modelClass);
}
viewdatabing.setVariable(viewmodelid,viewmodel);
getLifecycle().addObserver(viewmodel);
}
/**
* 创建ViewModel
*
* @param cls
* @param <T>
* @return
*/
public <T extends ViewModel> T createViewModel(FragmentActivity activity, Class<T> cls) {
return ViewModelProviders.of(activity).get(cls);
}
/**
* 初始化ViewModel
*
* @return 继承BaseViewModel的ViewModel
*/
public VM initViewModel() {
return null;
}
//设置标题头返回事件以及标题名称设置
public class TitleClickProxy {
private MutableLiveData<String> TitleName;
public boolean titlesearch = false;
//点击返回按钮事件
public void onClose() {
finish();
}
//点击搜索按钮事件
public void clickSearch(){
onClickSearch();
}
//设置标题是否显示,默认不显示
public void setTitlesearch(boolean titlesearch){
this.titlesearch = titlesearch;
}
//设置标题名称
public void setTitleName(String name){
getTitleName().setValue(name);
}
//获取值
public MutableLiveData<String> getTitleName() {
if(TitleName == null){
TitleName = new MutableLiveData<>();
}
return TitleName;
}
}
//设置装填栏透明
public static void fullScreen(Activity activity) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { //5.x开始需要把颜色设置透明,否则导航栏会呈现系统默认的浅灰色
Window window = activity.getWindow();
View decorView = window.getDecorView(); //两个 flag 要结合使用,表示让应用的主体内容占用系统状态栏的空间
int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
decorView.setSystemUiVisibility(option);
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(Color.TRANSPARENT);
} else {
Window window = activity.getWindow();
WindowManager.LayoutParams attributes = window.getAttributes();
int flagTranslucentStatus = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
int flagTranslucentNavigation = WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION;
attributes.flags |= flagTranslucentStatus;
window.setAttributes(attributes);
}
}
}
}
BaseViewModel 简单的写了一些 =。= 没有好好写 先讲究用了用
public abstract class BaseViewModel<M extends BaseModel> extends AndroidViewModel implements BaseLifecycle {
protected M model;
public BaseViewModel(@NonNull Application application) {
super(application);
}
public BaseViewModel(@NonNull Application application, M model) {
super(application);
this.model = model;
}
@Override
protected void onCleared() {
super.onCleared();
if (model != null) {
model.onCleared();
}
}
}
RecyclerBaseAdapter 这个是一个大神写的照着抄了过来(大神见谅)
public abstract class RecyclerBaseAdapter<M,B extends ViewDataBinding> extends RecyclerView.Adapter{
protected Context context;
//数据
protected ObservableArrayList<M> items;
//监听数据发生改变
protected ListChangedCallback itemsChangeCallback;
public ObservableArrayList<M> getItems() {
return items;
}
public RecyclerBaseAdapter(Context context) {
this.context = context;
items = new ObservableArrayList<>();
this.itemsChangeCallback = new ListChangedCallback();
}
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
B binding = DataBindingUtil.inflate(LayoutInflater.from(context),this.getLayoutResId(viewType),parent,false);
return new ViewHolder(binding,binding.getRoot());
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
B binding = DataBindingUtil.getBinding(holder.itemView);
this.onBindItem(binding,this.items.get(position));
}
@Override
public int getItemCount() {
return items.size();
}
@Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
this.items.addOnListChangedCallback(itemsChangeCallback);
}
@Override
public void onDetachedFromRecyclerView(RecyclerView recyclerView) {
super.onDetachedFromRecyclerView(recyclerView);
this.items.removeOnListChangedCallback(itemsChangeCallback);
}
class ViewHolder extends RecyclerView.ViewHolder{
public ViewHolder(B binding, @NonNull View itemView) {
super(itemView);
}
}
//数据刷新处理事件
private class ListChangedCallback extends ObservableArrayList.OnListChangedCallback<ObservableArrayList<M>> {
@Override
public void onChanged(ObservableArrayList<M> newItems) {
RecyclerBaseAdapter.this.onChanged(newItems);
}
@Override
public void onItemRangeChanged(ObservableArrayList<M> newItems, int i, int i1) {
RecyclerBaseAdapter.this.onItemRangeChanged(newItems, i, i1);
}
@Override
public void onItemRangeInserted(ObservableArrayList<M> newItems, int i, int i1) {
RecyclerBaseAdapter.this.onItemRangeInserted(newItems, i, i1);
}
@Override
public void onItemRangeMoved(ObservableArrayList<M> newItems, int i, int i1, int i2) {
RecyclerBaseAdapter.this.onItemRangeMoved(newItems);
}
@Override
public void onItemRangeRemoved(ObservableArrayList<M> sender, int positionStart, int itemCount) {
RecyclerBaseAdapter.this.onItemRangeRemoved(sender, positionStart, itemCount);
}
}
//region 处理数据集变化
protected void onChanged(ObservableArrayList<M> newItems) {
resetItems(newItems);
notifyDataSetChanged();
}
protected void onItemRangeChanged(ObservableArrayList<M> newItems, int positionStart, int itemCount) {
resetItems(newItems);
notifyItemRangeChanged(positionStart, itemCount);
}
protected void onItemRangeInserted(ObservableArrayList<M> newItems, int positionStart, int itemCount) {
resetItems(newItems);
notifyItemRangeInserted(positionStart, itemCount);
}
protected void onItemRangeMoved(ObservableArrayList<M> newItems) {
resetItems(newItems);
notifyDataSetChanged();
}
protected void onItemRangeRemoved(ObservableArrayList<M> newItems, int positionStart, int itemCount) {
resetItems(newItems);
notifyItemRangeRemoved(positionStart, itemCount);
}
protected void resetItems(ObservableArrayList<M> newItems) {
this.items = newItems;
}
//布局
protected abstract int getLayoutResId(int viewType);
//数据和样式改变
protected abstract void onBindItem(B binding, M m);
}
优化recyclerView同时添加了加载更多预加载方案
public abstract class EndlessRecyclerOnScrollListener extends RecyclerView.OnScrollListener {
public static String TAG = EndlessRecyclerOnScrollListener.class.getSimpleName();
public int previousTotal = 0; // The total number of items in the dataset after the last load 总数据
private boolean loading = true; // True if we are still waiting for the last set of data to load. 是否提前加载
public int visibleThreshold = 5; // The minimum amount of items to have below your current scroll position before loading more.
int firstVisibleItem, visibleItemCount, totalItemCount;
private int current_page = 1;
private LinearLayoutManager mLinearLayoutManager;
public EndlessRecyclerOnScrollListener(LinearLayoutManager linearLayoutManager) {
this.mLinearLayoutManager = linearLayoutManager;
}
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
visibleItemCount = recyclerView.getChildCount();
totalItemCount = mLinearLayoutManager.getItemCount();
firstVisibleItem = mLinearLayoutManager.findFirstVisibleItemPosition();
if (loading) {
if (totalItemCount > previousTotal) {
loading = false;
previousTotal = totalItemCount;
}
}
if (!loading && (totalItemCount - visibleItemCount) <= (firstVisibleItem + visibleThreshold)) {
// End has been reached
// Do something
current_page++;
onLoadMore(current_page);
loading = true;
}
}
public abstract void onLoadMore(int current_page);
public void reset(int previousTotal, boolean loading) {
this.previousTotal = previousTotal;
this.loading = loading;
}
}
endlessRecyclerOnScrollListener = new EndlessRecyclerOnScrollListener(linearLayoutManager) {
@Override
public void onLoadMore(int current_page) {
//数据添加
interfaceUpdateData.loadMore();
}
};
recyclerView.addOnScrollListener(endlessRecyclerOnScrollListener);