optimize code

androidx
Zhanty 5 years ago
parent 77682bbd1d
commit 92f605bca9
  1. 1
      lib_base/build.gradle
  2. 18
      lib_base/src/main/java/com/android/base/adapter/DataManager.java
  3. 6
      lib_base/src/main/java/com/android/base/adapter/ItemHelper.java
  4. 19
      lib_base/src/main/java/com/android/base/adapter/list/BaseListAdapter.java
  5. 5
      lib_base/src/main/java/com/android/base/adapter/list/ListDataManagerImpl.java
  6. 2
      lib_base/src/main/java/com/android/base/adapter/list/SmartViewHolder.java
  7. 2
      lib_base/src/main/java/com/android/base/adapter/list/ViewHolder.java
  8. 4
      lib_base/src/main/java/com/android/base/adapter/pager/RecycleBin.java
  9. 13
      lib_base/src/main/java/com/android/base/adapter/pager/RecyclingPagerAdapter.java
  10. 3
      lib_base/src/main/java/com/android/base/adapter/pager/ViewPagerAdapter.java
  11. 11
      lib_base/src/main/java/com/android/base/adapter/recycler/DiffRecyclerAdapter.java
  12. 8
      lib_base/src/main/java/com/android/base/adapter/recycler/MultiTypeAdapter.java
  13. 15
      lib_base/src/main/java/com/android/base/adapter/recycler/RecyclerAdapter.java
  14. 2
      lib_base/src/main/java/com/android/base/adapter/recycler/RecyclerDataManagerImpl.java
  15. 4
      lib_base/src/main/java/com/android/base/adapter/recycler/SimpleRecyclerAdapter.kt
  16. 3
      lib_base/src/main/java/com/android/base/adapter/recycler/SmartViewHolder.java
  17. 2
      lib_base/src/main/java/com/android/base/app/ApplicationDelegate.java
  18. 12
      lib_base/src/main/java/com/android/base/app/BaseAppContext.java
  19. 4
      lib_base/src/main/java/com/android/base/app/CrashHandler.java
  20. 33
      lib_base/src/main/java/com/android/base/app/Sword.java
  21. 1
      lib_base/src/main/java/com/android/base/app/aac/SingleLiveData.java
  22. 4
      lib_base/src/main/java/com/android/base/app/activity/BaseActivity.java
  23. 8
      lib_base/src/main/java/com/android/base/app/fragment/BaseDialogFragment.java
  24. 8
      lib_base/src/main/java/com/android/base/app/fragment/BaseFragment.java
  25. 3
      lib_base/src/main/java/com/android/base/app/fragment/FragmentInfo.java
  26. 24
      lib_base/src/main/java/com/android/base/app/fragment/Fragments.kt
  27. 6
      lib_base/src/main/java/com/android/base/app/ui/UIEx.kt
  28. 152
      lib_base/src/main/java/com/android/base/data/Resource.java
  29. 130
      lib_base/src/main/java/com/android/base/data/Resource.kt
  30. 6
      lib_base/src/main/java/com/android/base/data/Status.kt
  31. 1
      lib_base/src/main/java/com/android/base/imageloader/DisplayConfig.java
  32. 2
      lib_base/src/main/java/com/android/base/interfaces/ActivityLifecycleCallbacksAdapter.java
  33. 2
      lib_base/src/main/java/com/android/base/interfaces/DrawerListenerAdapter.java
  34. 2
      lib_base/src/main/java/com/android/base/interfaces/OnPageChangeListenerAdapter.java
  35. 2
      lib_base/src/main/java/com/android/base/interfaces/OnSeekBarChangeListenerAdapter.java
  36. 2
      lib_base/src/main/java/com/android/base/interfaces/OnTabSelectedListenerAdapter.java
  37. 2
      lib_base/src/main/java/com/android/base/interfaces/TextWatcherAdapter.java
  38. 2
      lib_base/src/main/java/com/android/base/interfaces/TransitionListenerAdapter.java
  39. 1
      lib_base/src/main/java/com/android/base/utils/android/SoftKeyboardUtils.java
  40. 3
      lib_base/src/main/java/com/android/base/utils/android/WindowUtils.java
  41. 15
      lib_base/src/main/java/com/android/base/utils/android/views/ListViewEx.kt
  42. 2
      lib_base/src/main/java/com/android/base/utils/android/views/TextViewEx.kt
  43. 52
      lib_base/src/main/java/com/android/base/utils/android/views/ViewEx.kt
  44. 2
      lib_base/src/main/java/com/android/base/widget/ScrollChildSwipeRefreshLayout.java
  45. 1
      lib_base/src/main/java/com/android/base/widget/pulltozoom/PullToZoomScrollView.java
  46. 16
      lib_base/src/main/java/com/android/base/widget/viewpager/BannerViewPager.java
  47. 2
      lib_base/src/main/java/com/android/base/widget/viewpager/IPagerNumberView.java
  48. 2
      lib_base/src/main/java/com/android/base/widget/viewpager/PageNumberView.kt
  49. 5
      lib_base/src/main/res/values/base_attrs.xml
  50. 4
      lib_base/src/test/java/com/android/base/rx/TestApplication.java
  51. 4
      lib_base/src/test/java/com/android/base/rx/TestListFragment.java
  52. 6
      lib_base/src/test/java/com/android/base/rx/TestStateFragment.java

@ -83,6 +83,7 @@ dependencies {
api androidLibraries.lifecycleViewModelKtx api androidLibraries.lifecycleViewModelKtx
api androidLibraries.lifecycleExtensions api androidLibraries.lifecycleExtensions
api androidLibraries.lifecycleReactiveStreams api androidLibraries.lifecycleReactiveStreams
api androidLibraries.ktx
//Kotlin //Kotlin
api kotlinLibraries.kotlinStdlib api kotlinLibraries.kotlinStdlib

@ -2,6 +2,8 @@ package com.android.base.adapter;
import java.util.List; import java.util.List;
import androidx.annotation.Nullable;
/** /**
* <pre> * <pre>
* 注意数据源引用的替换只有setDataSource方法会把elements替换掉之前的数据源引用其他方法都是基于现有数据集合做删除与添加操作 * 注意数据源引用的替换只有setDataSource方法会把elements替换掉之前的数据源引用其他方法都是基于现有数据集合做删除与添加操作
@ -13,7 +15,6 @@ import java.util.List;
*/ */
public interface DataManager<T> { public interface DataManager<T> {
//Add op
void add(T element); void add(T element);
void addAt(int location, T element); void addAt(int location, T element);
@ -21,7 +22,7 @@ public interface DataManager<T> {
void addItems(List<T> elements); void addItems(List<T> elements);
/** /**
* 添加元素前会使用equals方法进行比较荣旧的数据集合中删除相同的数据在添加 * 添加元素前会使用equals方法进行比较
* *
* @param elements 元素 * @param elements 元素
*/ */
@ -29,7 +30,6 @@ public interface DataManager<T> {
void addItemsAt(int location, List<T> elements); void addItemsAt(int location, List<T> elements);
//update op
void replace(T oldElement, T newElement); void replace(T oldElement, T newElement);
void replaceAt(int index, T element); void replaceAt(int index, T element);
@ -42,14 +42,13 @@ public interface DataManager<T> {
void replaceAll(List<T> elements); void replaceAll(List<T> elements);
/** /**
* 此方法会使用elements替换掉之前的数据源而不对之前的数据源做任何操作 * 此方法会使用 newDataSource 替换掉之前的数据源而不对之前的数据源做任何操作
* *
* @param newDataSource 新的数据集 * @param newDataSource 新的数据集
* @param notifyDataSetChanged 是否调用adapter的notifyDataSetChanged方法 * @param notifyDataSetChanged 是否调用adapter的notifyDataSetChanged方法
*/ */
void setDataSource(List<T> newDataSource, boolean notifyDataSetChanged); void setDataSource(List<T> newDataSource, boolean notifyDataSetChanged);
//remove opt
void remove(T element); void remove(T element);
void removeAt(int index); void removeAt(int index);
@ -58,26 +57,23 @@ public interface DataManager<T> {
void removeItems(List<T> elements, boolean isSuccessive); void removeItems(List<T> elements, boolean isSuccessive);
//get @Nullable
T getItem(int position); T getItem(int position);
List<T> getItems(); List<T> getItems();
int getDataSize(); int getDataSize();
//contains
boolean contains(T element); boolean contains(T element);
boolean isEmpty(); boolean isEmpty();
//clear opt
void clear(); void clear();
//Utils
/** /**
* @param t element * @param t element
* @return -1 if not contains this element * @return -1 if not contains this element
*/ */
int getItemPosition(T t); int indexItem(T t);
} }

@ -11,8 +11,8 @@ import androidx.annotation.StringRes;
/** /**
* @author Ztiany * @author Ztiany
* Email 1169654504@qq.com * Email 1169654504@qq.com
* Date 015-12-29 20:47 * Date 015-12-29 20:47
*/ */
public class ItemHelper { public class ItemHelper {
@ -24,7 +24,7 @@ public class ItemHelper {
views = new SparseArray<>(); views = new SparseArray<>();
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked,WeakerAccess")
public <T extends View> T getView(int viewId) { public <T extends View> T getView(int viewId) {
View view = views.get(viewId); View view = views.get(viewId);
if (view == null) { if (view == null) {

@ -12,6 +12,7 @@ import com.android.base.adapter.DataManager;
import java.util.List; import java.util.List;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
/** /**
* absListView通用的Adapter,注意只有setDataSource才能替换原有数据源的引用 * absListView通用的Adapter,注意只有setDataSource才能替换原有数据源的引用
@ -22,7 +23,7 @@ import androidx.annotation.NonNull;
@SuppressWarnings("unused") @SuppressWarnings("unused")
public abstract class BaseListAdapter<T, VH extends ViewHolder> extends BaseAdapter implements DataManager<T> { public abstract class BaseListAdapter<T, VH extends ViewHolder> extends BaseAdapter implements DataManager<T> {
protected final Context mContext; private final Context mContext;
private final static int ITEM_ID = R.id.base_item_tag_view_id; private final static int ITEM_ID = R.id.base_item_tag_view_id;
private DataManager<T> mDataManager; private DataManager<T> mDataManager;
private final LayoutInflater mLayoutInflater; private final LayoutInflater mLayoutInflater;
@ -38,6 +39,10 @@ public abstract class BaseListAdapter<T, VH extends ViewHolder> extends BaseAdap
mDataManager = new ListDataManagerImpl<>(data, this); mDataManager = new ListDataManagerImpl<>(data, this);
} }
public Context getContext() {
return mContext;
}
@Override @Override
public int getCount() { public int getCount() {
return getDataSize(); return getDataSize();
@ -66,7 +71,6 @@ public abstract class BaseListAdapter<T, VH extends ViewHolder> extends BaseAdap
return viewHolder.mItemView; return viewHolder.mItemView;
} }
@SuppressWarnings("all")
protected abstract void onBindData(@NonNull VH viewHolder, T item); protected abstract void onBindData(@NonNull VH viewHolder, T item);
@NonNull @NonNull
@ -82,11 +86,6 @@ public abstract class BaseListAdapter<T, VH extends ViewHolder> extends BaseAdap
return super.getViewTypeCount(); return super.getViewTypeCount();
} }
///////////////////////////////////////////////////////////////////////////
// DataManager
///////////////////////////////////////////////////////////////////////////
@Override @Override
public void add(T elem) { public void add(T elem) {
mDataManager.add(elem); mDataManager.add(elem);
@ -147,6 +146,7 @@ public abstract class BaseListAdapter<T, VH extends ViewHolder> extends BaseAdap
mDataManager.removeAt(index); mDataManager.removeAt(index);
} }
@Nullable
@Override @Override
public T getItem(int position) { public T getItem(int position) {
return mDataManager.getItem(position); return mDataManager.getItem(position);
@ -168,8 +168,8 @@ public abstract class BaseListAdapter<T, VH extends ViewHolder> extends BaseAdap
} }
@Override @Override
public int getItemPosition(T t) { public int indexItem(T t) {
return mDataManager.getItemPosition(t); return mDataManager.indexItem(t);
} }
@Override @Override
@ -181,4 +181,5 @@ public abstract class BaseListAdapter<T, VH extends ViewHolder> extends BaseAdap
public List<T> getItems() { public List<T> getItems() {
return mDataManager.getItems(); return mDataManager.getItems();
} }
} }

@ -8,6 +8,8 @@ import com.android.base.utils.common.Checker;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import androidx.annotation.Nullable;
final class ListDataManagerImpl<T> implements DataManager<T> { final class ListDataManagerImpl<T> implements DataManager<T> {
@ -137,6 +139,7 @@ final class ListDataManagerImpl<T> implements DataManager<T> {
} }
@Override @Override
@Nullable
public T getItem(int position) { public T getItem(int position) {
if (mData != null && mData.size() > position) { if (mData != null && mData.size() > position) {
return mData.get(position); return mData.get(position);
@ -168,7 +171,7 @@ final class ListDataManagerImpl<T> implements DataManager<T> {
} }
@Override @Override
public int getItemPosition(T t) { public int indexItem(T t) {
List<T> items = getItems(); List<T> items = getItems();
if (items == null) { if (items == null) {
return -1; return -1;

@ -7,7 +7,7 @@ import com.android.base.adapter.ItemHelper;
@SuppressWarnings("unused") @SuppressWarnings("unused")
public class SmartViewHolder extends ViewHolder { public class SmartViewHolder extends ViewHolder {
protected final ItemHelper mHelper; private final ItemHelper mHelper;
public SmartViewHolder(View itemView) { public SmartViewHolder(View itemView) {
super(itemView); super(itemView);

@ -4,7 +4,6 @@ import android.view.View;
public class ViewHolder { public class ViewHolder {
@SuppressWarnings("all")
protected final View mItemView; protected final View mItemView;
private int mPosition; private int mPosition;
private int mType; private int mType;
@ -32,4 +31,5 @@ public class ViewHolder {
public View getItemView() { public View getItemView() {
return mItemView; return mItemView;
} }
} }

@ -1,4 +1,4 @@
package com.android.base.adapter.pager.recycler; package com.android.base.adapter.pager;
import android.os.Build; import android.os.Build;
import android.util.SparseArray; import android.util.SparseArray;
@ -15,6 +15,7 @@ import android.view.View;
* is copyrighted 2006 The Android Open Source Project. * is copyrighted 2006 The Android Open Source Project.
*/ */
public class RecycleBin { public class RecycleBin {
/** /**
* Views that were on screen at the start of layout. This array is populated at the start of * Views that were on screen at the start of layout. This array is populated at the start of
* layout, and at the end of layout all view in activeViews are moved to scrapViews. * layout, and at the end of layout all view in activeViews are moved to scrapViews.
@ -149,4 +150,5 @@ public class RecycleBin {
return null; return null;
} }
} }
} }

@ -1,9 +1,11 @@
package com.android.base.adapter.pager.recycler; package com.android.base.adapter.pager;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
import android.widget.AdapterView; import android.widget.AdapterView;
import org.jetbrains.annotations.NotNull;
import androidx.viewpager.widget.PagerAdapter; import androidx.viewpager.widget.PagerAdapter;
/** /**
@ -33,7 +35,7 @@ public abstract class RecyclingPagerAdapter extends PagerAdapter {
} }
@Override @Override
public final Object instantiateItem(ViewGroup container, int position) { public final Object instantiateItem(@NotNull ViewGroup container, int position) {
int viewType = getItemViewType(position); int viewType = getItemViewType(position);
View view = null; View view = null;
if (viewType != IGNORE_ITEM_VIEW_TYPE) { if (viewType != IGNORE_ITEM_VIEW_TYPE) {
@ -45,7 +47,7 @@ public abstract class RecyclingPagerAdapter extends PagerAdapter {
} }
@Override @Override
public final void destroyItem(ViewGroup container, int position, Object object) { public final void destroyItem(ViewGroup container, int position, @NotNull Object object) {
View view = (View) object; View view = (View) object;
container.removeView(view); container.removeView(view);
int viewType = getItemViewType(position); int viewType = getItemViewType(position);
@ -55,7 +57,7 @@ public abstract class RecyclingPagerAdapter extends PagerAdapter {
} }
@Override @Override
public final boolean isViewFromObject(View view, Object object) { public final boolean isViewFromObject(@NotNull View view, @NotNull Object object) {
return view == object; return view == object;
} }
@ -108,8 +110,9 @@ public abstract class RecyclingPagerAdapter extends PagerAdapter {
* Heterogeneous lists can specify their number of view types, so that this View is * Heterogeneous lists can specify their number of view types, so that this View is
* always of the right type (see {@link #getViewTypeCount()} and * always of the right type (see {@link #getViewTypeCount()} and
* {@link #getItemViewType(int)}). * {@link #getItemViewType(int)}).
* @param parent The parent that this view will eventually be attached to * @param container The parent that this view will eventually be attached to
* @return A View corresponding to the data at the specified position. * @return A View corresponding to the data at the specified position.
*/ */
public abstract View getView(int position, View convertView, ViewGroup container); public abstract View getView(int position, View convertView, ViewGroup container);
} }

@ -4,7 +4,6 @@ import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
import com.android.base.R; import com.android.base.R;
import com.android.base.adapter.pager.recycler.RecyclingPagerAdapter;
import com.android.base.utils.common.Checker; import com.android.base.utils.common.Checker;
import java.util.List; import java.util.List;
@ -13,7 +12,7 @@ import androidx.annotation.NonNull;
import androidx.annotation.Nullable; import androidx.annotation.Nullable;
/** /**
* 如果使用可缩放的 View 作为 pager可能不适合使用此Adapter * 如果使用可缩放的 View 作为 pager可能不适合使用此 Adapter
* *
* @param <T> 数据 * @param <T> 数据
* @param <VH> View Holder类型 * @param <VH> View Holder类型

@ -30,7 +30,7 @@ import androidx.recyclerview.widget.RecyclerView;
public abstract class DiffRecyclerAdapter<T, VH extends ViewHolder> extends RecyclerView.Adapter<VH> implements DataManager<T> { public abstract class DiffRecyclerAdapter<T, VH extends ViewHolder> extends RecyclerView.Adapter<VH> implements DataManager<T> {
@NonNull @NonNull
protected Context mContext; private Context mContext;
private AsyncListDiffer<T> mAsyncListDiffer; private AsyncListDiffer<T> mAsyncListDiffer;
@ -67,6 +67,11 @@ public abstract class DiffRecyclerAdapter<T, VH extends ViewHolder> extends Recy
} }
} }
@NonNull
public Context getContext() {
return mContext;
}
@Override @Override
public int getItemCount() { public int getItemCount() {
return getDataSize(); return getDataSize();
@ -85,7 +90,7 @@ public abstract class DiffRecyclerAdapter<T, VH extends ViewHolder> extends Recy
public abstract void onBindViewHolder(@NonNull VH viewHolder, int position); public abstract void onBindViewHolder(@NonNull VH viewHolder, int position);
public void notifyEntryChanged(T t) { public void notifyEntryChanged(T t) {
int itemPosition = getItemPosition(t); int itemPosition = indexItem(t);
if (itemPosition != -1) { if (itemPosition != -1) {
notifyItemChanged(itemPosition); notifyItemChanged(itemPosition);
} }
@ -246,7 +251,7 @@ public abstract class DiffRecyclerAdapter<T, VH extends ViewHolder> extends Recy
} }
@Override @Override
public int getItemPosition(T t) { public int indexItem(T t) {
return isEmpty() ? -1 : getItems().indexOf(t); return isEmpty() ? -1 : getItems().indexOf(t);
} }

@ -8,6 +8,7 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
/** /**
@ -45,7 +46,7 @@ public class MultiTypeAdapter extends com.drakeet.multitype.MultiTypeAdapter imp
@SuppressWarnings("unused") @SuppressWarnings("unused")
public void notifyEntryChanged(Object entry) { public void notifyEntryChanged(Object entry) {
int itemPosition = getItemPosition(entry); int itemPosition = indexItem(entry);
if (itemPosition != -1) { if (itemPosition != -1) {
notifyItemChanged(itemPosition); notifyItemChanged(itemPosition);
} }
@ -117,6 +118,7 @@ public class MultiTypeAdapter extends com.drakeet.multitype.MultiTypeAdapter imp
mRecyclerDataManager.removeItems(elements, isSuccessive); mRecyclerDataManager.removeItems(elements, isSuccessive);
} }
@Nullable
@Override @Override
public Object getItem(int position) { public Object getItem(int position) {
return mRecyclerDataManager.getItem(position); return mRecyclerDataManager.getItem(position);
@ -149,8 +151,8 @@ public class MultiTypeAdapter extends com.drakeet.multitype.MultiTypeAdapter imp
} }
@Override @Override
public int getItemPosition(Object o) { public int indexItem(Object o) {
return mRecyclerDataManager.getItemPosition(o); return mRecyclerDataManager.indexItem(o);
} }
@Override @Override

@ -8,6 +8,7 @@ import com.android.base.adapter.DataManager;
import java.util.List; import java.util.List;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView; import androidx.recyclerview.widget.RecyclerView;
/** /**
@ -24,7 +25,7 @@ public abstract class RecyclerAdapter<T, VH extends ViewHolder> extends Recycler
private RecyclerDataManagerImpl<T> mDataManager; private RecyclerDataManagerImpl<T> mDataManager;
@NonNull @NonNull
protected final Context mContext; private final Context mContext;
public RecyclerAdapter(@NonNull Context context, List<T> data) { public RecyclerAdapter(@NonNull Context context, List<T> data) {
mDataManager = new RecyclerDataManagerImpl<>(data, this); mDataManager = new RecyclerDataManagerImpl<>(data, this);
@ -35,6 +36,11 @@ public abstract class RecyclerAdapter<T, VH extends ViewHolder> extends Recycler
this(context, null); this(context, null);
} }
@NonNull
public Context getContext() {
return mContext;
}
@Override @Override
public int getItemCount() { public int getItemCount() {
return getDataSize(); return getDataSize();
@ -53,7 +59,7 @@ public abstract class RecyclerAdapter<T, VH extends ViewHolder> extends Recycler
public abstract void onBindViewHolder(@NonNull VH viewHolder, int position); public abstract void onBindViewHolder(@NonNull VH viewHolder, int position);
public void notifyEntryChanged(T t) { public void notifyEntryChanged(T t) {
int itemPosition = getItemPosition(t); int itemPosition = indexItem(t);
if (itemPosition != -1) { if (itemPosition != -1) {
notifyItemChanged(itemPosition); notifyItemChanged(itemPosition);
} }
@ -123,6 +129,7 @@ public abstract class RecyclerAdapter<T, VH extends ViewHolder> extends Recycler
mDataManager.removeAt(index); mDataManager.removeAt(index);
} }
@Nullable
@Override @Override
public T getItem(int position) { public T getItem(int position) {
return mDataManager.getItem(position); return mDataManager.getItem(position);
@ -163,8 +170,8 @@ public abstract class RecyclerAdapter<T, VH extends ViewHolder> extends Recycler
} }
@Override @Override
public int getItemPosition(T t) { public int indexItem(T t) {
return mDataManager.getItemPosition(t); return mDataManager.indexItem(t);
} }
} }

@ -218,7 +218,7 @@ final class RecyclerDataManagerImpl<T> implements DataManager<T> {
} }
@Override @Override
public int getItemPosition(T t) { public int indexItem(T t) {
List<T> items = getItems(); List<T> items = getItems();
if (items == null) { if (items == null) {
return -1; return -1;

@ -14,7 +14,7 @@ import android.view.ViewGroup
*/ */
abstract class SimpleRecyclerAdapter<T>(context: Context, data: List<T>? = null) : RecyclerAdapter<T, KtViewHolder>(context, data) { abstract class SimpleRecyclerAdapter<T>(context: Context, data: List<T>? = null) : RecyclerAdapter<T, KtViewHolder>(context, data) {
private var layoutInflater: LayoutInflater = LayoutInflater.from(mContext) private var layoutInflater: LayoutInflater = LayoutInflater.from(context)
final override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): KtViewHolder { final override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): KtViewHolder {
val layout = provideLayout(parent, viewType) val layout = provideLayout(parent, viewType)
@ -33,7 +33,7 @@ abstract class SimpleRecyclerAdapter<T>(context: Context, data: List<T>? = null)
abstract fun provideLayout(parent: ViewGroup, viewType: Int): Any abstract fun provideLayout(parent: ViewGroup, viewType: Int): Any
override fun onBindViewHolder(viewHolder: KtViewHolder, position: Int) { override fun onBindViewHolder(viewHolder: KtViewHolder, position: Int) {
bind(viewHolder, getItem(position)) bind(viewHolder, getItem(position) ?: throw NullPointerException("SimpleRecyclerAdapter onBindViewHolder getItem return null"))
} }
protected abstract fun bind(viewHolder: KtViewHolder, item: T) protected abstract fun bind(viewHolder: KtViewHolder, item: T)

@ -7,8 +7,7 @@ import com.android.base.adapter.ItemHelper;
public class SmartViewHolder extends ViewHolder { public class SmartViewHolder extends ViewHolder {
@SuppressWarnings("all") private final ItemHelper mHelper;
protected final ItemHelper mHelper;
public SmartViewHolder(View itemView) { public SmartViewHolder(View itemView) {
super(itemView); super(itemView);

@ -103,7 +103,7 @@ public final class ApplicationDelegate {
return mAppStatus; return mAppStatus;
} }
void setCrashProcessor(BaseKit.CrashProcessor crashProcessor) { void setCrashProcessor(Sword.CrashProcessor crashProcessor) {
if (mCrashHandler != null) { if (mCrashHandler != null) {
mCrashHandler.setCrashProcessor(crashProcessor); mCrashHandler.setCrashProcessor(crashProcessor);
} }

@ -10,37 +10,37 @@ public class BaseAppContext extends Application {
@Override @Override
protected void attachBaseContext(Context base) { protected void attachBaseContext(Context base) {
super.attachBaseContext(base); super.attachBaseContext(base);
BaseKit.get().getApplicationDelegate().attachBaseContext(base); Sword.get().getApplicationDelegate().attachBaseContext(base);
} }
@Override @Override
public void onCreate() { public void onCreate() {
super.onCreate(); super.onCreate();
BaseKit.get().getApplicationDelegate().onCreate(this); Sword.get().getApplicationDelegate().onCreate(this);
} }
@Override @Override
public void onLowMemory() { public void onLowMemory() {
super.onLowMemory(); super.onLowMemory();
BaseKit.get().getApplicationDelegate().onLowMemory(); Sword.get().getApplicationDelegate().onLowMemory();
} }
@Override @Override
public void onTrimMemory(int level) { public void onTrimMemory(int level) {
super.onTrimMemory(level); super.onTrimMemory(level);
BaseKit.get().getApplicationDelegate().onTrimMemory(level); Sword.get().getApplicationDelegate().onTrimMemory(level);
} }
@Override @Override
public void onConfigurationChanged(Configuration newConfig) { public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig); super.onConfigurationChanged(newConfig);
BaseKit.get().getApplicationDelegate().onConfigurationChanged(newConfig); Sword.get().getApplicationDelegate().onConfigurationChanged(newConfig);
} }
@Override @Override
public void onTerminate() { public void onTerminate() {
super.onTerminate(); super.onTerminate();
BaseKit.get().getApplicationDelegate().onTerminate(); Sword.get().getApplicationDelegate().onTerminate();
} }
} }

@ -22,7 +22,7 @@ import timber.log.Timber;
final class CrashHandler implements Thread.UncaughtExceptionHandler { final class CrashHandler implements Thread.UncaughtExceptionHandler {
private Context mContext; private Context mContext;
private BaseKit.CrashProcessor mCrashProcessor; private Sword.CrashProcessor mCrashProcessor;
public static CrashHandler register(Application application) { public static CrashHandler register(Application application) {
CrashHandler crashHandler = new CrashHandler(application); CrashHandler crashHandler = new CrashHandler(application);
@ -30,7 +30,7 @@ final class CrashHandler implements Thread.UncaughtExceptionHandler {
return crashHandler; return crashHandler;
} }
void setCrashProcessor(BaseKit.CrashProcessor crashProcessor) { void setCrashProcessor(Sword.CrashProcessor crashProcessor) {
mCrashProcessor = crashProcessor; mCrashProcessor = crashProcessor;
} }

@ -11,7 +11,7 @@ import com.android.base.app.fragment.LoadingViewFactory;
import com.android.base.app.ui.PageNumber; import com.android.base.app.ui.PageNumber;
import com.android.base.app.ui.RefreshLoadViewFactory; import com.android.base.app.ui.RefreshLoadViewFactory;
import com.android.base.app.ui.RefreshViewFactory; import com.android.base.app.ui.RefreshViewFactory;
import com.android.base.interfaces.adapter.ActivityLifecycleCallbacksAdapter; import com.android.base.interfaces.ActivityLifecycleCallbacksAdapter;
import com.android.base.receiver.NetworkState; import com.android.base.receiver.NetworkState;
import com.blankj.utilcode.util.ActivityUtils; import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.AppUtils; import com.blankj.utilcode.util.AppUtils;
@ -27,22 +27,23 @@ import dagger.android.support.AndroidSupportInjection;
import io.reactivex.Flowable; import io.reactivex.Flowable;
/** /**
* 基础库工具 * useful tools for android development, just like a sword.
* *
* @author Ztiany * @author Ztiany
* Email: ztiany3@gmail.com * Email: ztiany3@gmail.com
* Date : 2018-04-16 17:12 * Date : 2018-04-16 17:12
*/ */
@SuppressWarnings("unused")
@UiThread @UiThread
public final class BaseKit { public final class Sword {
private static final BaseKit ONLY_BASE = new BaseKit(); private static final Sword ONLY_BASE = new Sword();
private BaseKit() { private Sword() {
mApplicationDelegate = new ApplicationDelegate(); mApplicationDelegate = new ApplicationDelegate();
} }
public static BaseKit get() { public static Sword get() {
return ONLY_BASE; return ONLY_BASE;
} }
@ -64,12 +65,11 @@ public final class BaseKit {
/** /**
* 获取 Application 代理 * 获取 Application 代理
*/ */
@SuppressWarnings("WeakerAccess")
public ApplicationDelegate getApplicationDelegate() { public ApplicationDelegate getApplicationDelegate() {
return mApplicationDelegate; return mApplicationDelegate;
} }
public BaseKit registerLoadingFactory(LoadingViewFactory loadingViewFactory) { public Sword registerLoadingFactory(LoadingViewFactory loadingViewFactory) {
if (mLoadingViewFactory != null) { if (mLoadingViewFactory != null) {
throw new UnsupportedOperationException("LoadingViewFactory had already set"); throw new UnsupportedOperationException("LoadingViewFactory had already set");
} }
@ -93,17 +93,17 @@ public final class BaseKit {
void uncaughtException(Thread thread, Throwable ex); void uncaughtException(Thread thread, Throwable ex);
} }
public BaseKit setCrashProcessor(CrashProcessor crashProcessor) { public Sword setCrashProcessor(CrashProcessor crashProcessor) {
mApplicationDelegate.setCrashProcessor(crashProcessor); mApplicationDelegate.setCrashProcessor(crashProcessor);
return this; return this;
} }
public BaseKit setDefaultPageStart(int pageStart) { public Sword setDefaultPageStart(int pageStart) {
PageNumber.setDefaultPageStart(pageStart); PageNumber.setDefaultPageStart(pageStart);
return this; return this;
} }
public BaseKit setDefaultPageSize(int defaultPageSize) { public Sword setDefaultPageSize(int defaultPageSize) {
PageNumber.setDefaultPageSize(defaultPageSize); PageNumber.setDefaultPageSize(defaultPageSize);
return this; return this;
} }
@ -113,12 +113,12 @@ public final class BaseKit {
* *
* @param defaultContainerId 容器id * @param defaultContainerId 容器id
*/ */
public BaseKit setDefaultFragmentContainerId(int defaultContainerId) { public Sword setDefaultFragmentContainerId(int defaultContainerId) {
FragmentConfig.setDefaultContainerId(defaultContainerId); FragmentConfig.setDefaultContainerId(defaultContainerId);
return this; return this;
} }
public BaseKit enableAutoInject() { public Sword enableAutoInject() {
Application.ActivityLifecycleCallbacks activityLifecycleCallbacks = new ActivityLifecycleCallbacksAdapter() { Application.ActivityLifecycleCallbacks activityLifecycleCallbacks = new ActivityLifecycleCallbacksAdapter() {
@Override @Override
@ -182,8 +182,7 @@ public final class BaseKit {
boolean isServerError(Throwable throwable); boolean isServerError(Throwable throwable);
} }
@SuppressWarnings("all") public Sword setErrorClassifier(ErrorClassifier errorClassifier) {
public BaseKit setErrorClassifier(ErrorClassifier errorClassifier) {
if (mErrorClassifier != null) { if (mErrorClassifier != null) {
throw new UnsupportedOperationException("ErrorClassifier had already set"); throw new UnsupportedOperationException("ErrorClassifier had already set");
} }
@ -195,12 +194,12 @@ public final class BaseKit {
return mErrorClassifier; return mErrorClassifier;
} }
public BaseKit registerRefreshLoadViewFactory(RefreshLoadViewFactory.Factory factory) { public Sword registerRefreshLoadViewFactory(RefreshLoadViewFactory.Factory factory) {
RefreshLoadViewFactory.registerFactory(factory); RefreshLoadViewFactory.registerFactory(factory);
return this; return this;
} }
public BaseKit registerRefreshViewFactory(RefreshViewFactory.Factory factory) { public Sword registerRefreshViewFactory(RefreshViewFactory.Factory factory) {
RefreshViewFactory.registerFactory(factory); RefreshViewFactory.registerFactory(factory);
return this; return this;
} }

@ -19,7 +19,6 @@ public class SingleLiveData<T> extends MediatorLiveData<T> {
private final List<WeakReference<ObserverWrapper<? super T>>> mWrapperObserverList = new ArrayList<>(); private final List<WeakReference<ObserverWrapper<? super T>>> mWrapperObserverList = new ArrayList<>();
@Override @Override
public void setValue(T value) { public void setValue(T value) {
mVersion++; mVersion++;

@ -7,6 +7,8 @@ import android.view.View;
import com.android.base.utils.android.compat.AndroidVersion; import com.android.base.utils.android.compat.AndroidVersion;
import com.github.dmstocking.optional.java.util.function.Predicate; import com.github.dmstocking.optional.java.util.function.Predicate;
import org.jetbrains.annotations.NotNull;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import androidx.annotation.Nullable; import androidx.annotation.Nullable;
import androidx.annotation.UiThread; import androidx.annotation.UiThread;
@ -121,7 +123,7 @@ public abstract class BaseActivity extends AppCompatActivity implements Activity
} }
@Override @Override
protected void onSaveInstanceState(Bundle outState) { protected void onSaveInstanceState(@NotNull Bundle outState) {
super.onSaveInstanceState(outState); super.onSaveInstanceState(outState);
mActivityDelegates.callOnSaveInstanceState(outState); mActivityDelegates.callOnSaveInstanceState(outState);
} }

@ -7,12 +7,14 @@ import android.view.LayoutInflater;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
import com.android.base.app.BaseKit; import com.android.base.app.Sword;
import com.android.base.app.activity.BackHandlerHelper; import com.android.base.app.activity.BackHandlerHelper;
import com.android.base.app.activity.OnBackPressListener; import com.android.base.app.activity.OnBackPressListener;
import com.android.base.app.ui.LoadingView; import com.android.base.app.ui.LoadingView;
import com.github.dmstocking.optional.java.util.function.Predicate; import com.github.dmstocking.optional.java.util.function.Predicate;
import org.jetbrains.annotations.NotNull;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import androidx.annotation.Nullable; import androidx.annotation.Nullable;
import androidx.annotation.StringRes; import androidx.annotation.StringRes;
@ -49,7 +51,7 @@ public class BaseDialogFragment extends AppCompatDialogFragment implements Loadi
} }
@Override @Override
public void onAttach(Context context) { public void onAttach(@NotNull Context context) {
super.onAttach(context); super.onAttach(context);
Timber.tag(tag()).d("onAttach() called with: context = [" + context + "]"); Timber.tag(tag()).d("onAttach() called with: context = [" + context + "]");
mFragmentDelegates.onAttach(context); mFragmentDelegates.onAttach(context);
@ -235,7 +237,7 @@ public class BaseDialogFragment extends AppCompatDialogFragment implements Loadi
private LoadingView getLoadingViewImpl() { private LoadingView getLoadingViewImpl() {
if (mLoadingViewImpl == null) { if (mLoadingViewImpl == null) {
mLoadingViewImpl = BaseKit.get().getLoadingViewFactory().createLoadingDelegate(getContext()); mLoadingViewImpl = Sword.get().getLoadingViewFactory().createLoadingDelegate(getContext());
} }
return mLoadingViewImpl; return mLoadingViewImpl;
} }

@ -8,12 +8,14 @@ import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
import android.view.ViewParent; import android.view.ViewParent;
import com.android.base.app.BaseKit; import com.android.base.app.Sword;
import com.android.base.app.activity.BackHandlerHelper; import com.android.base.app.activity.BackHandlerHelper;
import com.android.base.app.activity.OnBackPressListener; import com.android.base.app.activity.OnBackPressListener;
import com.android.base.app.ui.LoadingView; import com.android.base.app.ui.LoadingView;
import com.github.dmstocking.optional.java.util.function.Predicate; import com.github.dmstocking.optional.java.util.function.Predicate;
import org.jetbrains.annotations.NotNull;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import androidx.annotation.Nullable; import androidx.annotation.Nullable;
import androidx.annotation.StringRes; import androidx.annotation.StringRes;
@ -50,7 +52,7 @@ public class BaseFragment extends Fragment implements LoadingView, OnBackPressLi
} }
@Override @Override
public void onAttach(Context context) { public void onAttach(@NotNull Context context) {
super.onAttach(context); super.onAttach(context);
Timber.tag(tag()).d("onAttach() called with: context = [" + context + "]"); Timber.tag(tag()).d("onAttach() called with: context = [" + context + "]");
mFragmentDelegates.onAttach(context); mFragmentDelegates.onAttach(context);
@ -249,7 +251,7 @@ public class BaseFragment extends Fragment implements LoadingView, OnBackPressLi
mLoadingViewImpl = onCreateLoadingView(); mLoadingViewImpl = onCreateLoadingView();
} }
if (mLoadingViewImpl == null) { if (mLoadingViewImpl == null) {
mLoadingViewImpl = BaseKit.get().getLoadingViewFactory().createLoadingDelegate(getContext()); mLoadingViewImpl = Sword.get().getLoadingViewFactory().createLoadingDelegate(getContext());
} }
return mLoadingViewImpl; return mLoadingViewImpl;
} }

@ -2,10 +2,11 @@ package com.android.base.app.fragment;
import android.content.Context; import android.content.Context;
import android.os.Bundle; import android.os.Bundle;
import androidx.fragment.app.Fragment;
import java.lang.ref.WeakReference; import java.lang.ref.WeakReference;
import androidx.fragment.app.Fragment;
@SuppressWarnings("WeakerAccess,unused") @SuppressWarnings("WeakerAccess,unused")
public class FragmentInfo { public class FragmentInfo {

@ -173,7 +173,7 @@ fun <T> T.inSafelyFragmentTransaction(
var delegate = findDelegate { var delegate = findDelegate {
it is SafelyFragmentTransactionActivityDelegate it is SafelyFragmentTransactionActivityDelegate
}as? SafelyFragmentTransactionActivityDelegate } as? SafelyFragmentTransactionActivityDelegate
if (delegate == null) { if (delegate == null) {
delegate = SafelyFragmentTransactionActivityDelegate() delegate = SafelyFragmentTransactionActivityDelegate()
@ -241,22 +241,22 @@ private class SafelyFragmentTransactionActivityDelegate : ActivityDelegate<Fragm
private class SafelyFragmentTransactionFragmentDelegate : FragmentDelegate<Fragment> { private class SafelyFragmentTransactionFragmentDelegate : FragmentDelegate<Fragment> {
private val mPendingTransactions = mutableListOf<FragmentTransaction>() private val pendingTransactions = mutableListOf<FragmentTransaction>()
fun safeCommit(@NonNull fragment: Fragment, @NonNull transaction: FragmentTransaction): Boolean { fun safeCommit(@NonNull fragment: Fragment, @NonNull transaction: FragmentTransaction): Boolean {
return if (fragment.isResumed) { return if (fragment.isResumed) {
transaction.commit() transaction.commit()
false false
} else { } else {
mPendingTransactions.add(transaction) pendingTransactions.add(transaction)
true true
} }
} }
override fun onResume() { override fun onResume() {
if (mPendingTransactions.isNotEmpty()) { if (pendingTransactions.isNotEmpty()) {
mPendingTransactions.forEach { it.commit() } pendingTransactions.forEach { it.commit() }
mPendingTransactions.clear() pendingTransactions.clear()
} }
} }
@ -273,7 +273,7 @@ class EnhanceFragmentTransaction constructor(
/** /**
* [fragment] 添加到回退栈中 hide 其他 fragment * [fragment] 添加到回退栈中 hide 其他 fragment
* 如果 [containerId]==0则使用 [com.android.base.app.BaseKit.setDefaultFragmentContainerId] 中配置的 id * 如果 [containerId]==0则使用 [com.android.base.app.Sword.setDefaultFragmentContainerId] 中配置的 id
* 如果 [tag] ==null 则使用 fragment 对应 class 的全限定类名 * 如果 [tag] ==null 则使用 fragment 对应 class 的全限定类名
*/ */
fun addWithStack(containerId: Int = 0, fragment: Fragment, tag: String? = null, transition: Boolean = true): EnhanceFragmentTransaction { fun addWithStack(containerId: Int = 0, fragment: Fragment, tag: String? = null, transition: Boolean = true): EnhanceFragmentTransaction {
@ -292,7 +292,7 @@ class EnhanceFragmentTransaction constructor(
} }
/** /**
* replace 方式把 [fragment] 添加到回退栈中如果 [containerId]==0则使用 [com.android.base.app.BaseKit.setDefaultFragmentContainerId] 中配置的 id * replace 方式把 [fragment] 添加到回退栈中如果 [containerId]==0则使用 [com.android.base.app.Sword.setDefaultFragmentContainerId] 中配置的 id
* 如果 [tag] ==null 则使用 fragment 对应 class 的全限定类名 * 如果 [tag] ==null 则使用 fragment 对应 class 的全限定类名
*/ */
fun replaceWithStack(containerId: Int = 0, fragment: Fragment, tag: String? = null, transition: Boolean = true): EnhanceFragmentTransaction { fun replaceWithStack(containerId: Int = 0, fragment: Fragment, tag: String? = null, transition: Boolean = true): EnhanceFragmentTransaction {
@ -317,17 +317,17 @@ class EnhanceFragmentTransaction constructor(
} }
/** /**
* 添加 [fragment]默认使用 [com.android.base.app.BaseKit.setDefaultFragmentContainerId] 中配置的 id如果 [tag] 为null则使用 [fragment] 的全限定类 * 添加 [fragment]默认使用 [com.android.base.app.Sword.setDefaultFragmentContainerId] 中配置的 id如果 [tag] 为null则使用 [fragment] 的全限定类
*/ */
fun addWithDefaultContainer(fragment: Fragment, tag: String? = null): FragmentTransaction { fun addFragment(fragment: Fragment, tag: String? = null): FragmentTransaction {
val nonnullTag = (tag ?: fragment.javaClassName()) val nonnullTag = (tag ?: fragment.javaClassName())
return fragmentTransaction.add(FragmentConfig.defaultContainerId(), fragment, nonnullTag) return fragmentTransaction.add(FragmentConfig.defaultContainerId(), fragment, nonnullTag)
} }
/** /**
* 替换为 [fragment]id 使用 [com.android.base.app.BaseKit.setDefaultFragmentContainerId] 中配置的 id如果 [tag] 为null则使用 [fragment] 的全限定类名 * 替换为 [fragment]id 使用 [com.android.base.app.Sword.setDefaultFragmentContainerId] 中配置的 id如果 [tag] 为null则使用 [fragment] 的全限定类名
*/ */
fun replaceWithDefaultContainer(fragment: Fragment, tag: String? = null, transition: Boolean = true): FragmentTransaction { fun replaceFragment(fragment: Fragment, tag: String? = null, transition: Boolean = true): FragmentTransaction {
val nonnullTag = (tag ?: fragment.javaClassName()) val nonnullTag = (tag ?: fragment.javaClassName())
if (transition) { if (transition) {
setOpeningTransition() setOpeningTransition()

@ -2,7 +2,7 @@
package com.android.base.app.ui package com.android.base.app.ui
import com.android.base.app.BaseKit import com.android.base.app.Sword
import com.android.base.utils.common.isEmpty import com.android.base.utils.common.isEmpty
import timber.log.Timber import timber.log.Timber
@ -91,7 +91,7 @@ fun RefreshListLayout<*>.processListErrorWithStatus(throwable: Throwable) {
loadMoreFailed() loadMoreFailed()
} }
if (isEmpty) { if (isEmpty) {
val errorTypeClassifier = BaseKit.get().errorClassifier() val errorTypeClassifier = Sword.get().errorClassifier()
if (errorTypeClassifier != null) { if (errorTypeClassifier != null) {
when { when {
errorTypeClassifier.isNetworkError(throwable) -> showNetErrorLayout() errorTypeClassifier.isNetworkError(throwable) -> showNetErrorLayout()
@ -145,7 +145,7 @@ fun RefreshStateLayout.processErrorWithStatus(throwable: Throwable?) {
if (isRefreshing) { if (isRefreshing) {
refreshCompleted() refreshCompleted()
} }
val errorTypeClassifier = BaseKit.get().errorClassifier() val errorTypeClassifier = Sword.get().errorClassifier()
if (errorTypeClassifier != null) { if (errorTypeClassifier != null) {
when { when {
errorTypeClassifier.isNetworkError(throwable) -> { errorTypeClassifier.isNetworkError(throwable) -> {

@ -1,152 +0,0 @@
package com.android.base.data;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
/**
* @author Ztiany
* Email: ztiany3@gmail.com
* Date : 2018-05-15 16:23
*/
public class Resource<T> {
private final Throwable mError;
private final Status mStatus;
private final T mData; //data or default data
private Resource(Throwable error, T data, Status status) {
mError = error;
mStatus = status;
mData = data;
}
public boolean isSuccess() {
return mStatus == Status.SUCCESS;
}
public boolean isNoChange() {
return mStatus == Status.NOT_CHANGED;
}
public boolean isLoading() {
return mStatus == Status.LOADING;
}
public final boolean isError() {
return mStatus == Status.ERROR;
}
public final boolean hasData() {
return mData != null;
}
public static <T> Resource<T> success() {
return new Resource<>(null, null, Status.SUCCESS);
}
public static <T> Resource<T> success(@Nullable T data) {
return new Resource<>(null, data, Status.SUCCESS);
}
public static <T> Resource<T> error(@NonNull Throwable error) {
return error(error, null);
}
/**
* 创建一个 error 状态且设置一个默认的数据
*/
public static <T> Resource<T> error(@NonNull Throwable error, T defaultValue) {
return new Resource<>(error, defaultValue, Status.ERROR);
}
public static <T> Resource<T> loading() {
return loading(null);
}
/**
* 创建一个 loading 状态且设置一个默认的数据
*/
public static <T> Resource<T> loading(T defaultValue) {
return new Resource<>(null, defaultValue, Status.LOADING);
}
/**
* 如果数据源(比如 Repository)缓存了上一次请求的数据然后对其当前请求返回的数据发现数据是一样的可以使用此状态表示
*
* @return Resource
*/
public static Resource noChange() {
return new Resource<>(null, null, Status.NOT_CHANGED);
}
/**
* 获取 Resource 中保存的数据只有在 success 状态并且存在数据时下才能调用此方法否则将抛出异常
*
* @return Resource 中保存的数据
* @throws UnsupportedOperationException success 状态调用此方法
* @throws NullPointerException Resource 中没有保存数据时调用此方法
*/
@NonNull
public T data() {
if (isError() || isLoading() || isNoChange()) {
throw new UnsupportedOperationException("This method can only be called when the state success");
}
if (mData == null) {
throw new NullPointerException("Data is null");
}
return mData;
}
/**
* 获取 Resource 中保存的数据如果不存在数据则返回 defaultData 所设置的默认数据在不同状态下获取的数据具有不同的意义
*
* <pre>
* <li>success 状态下返回一个成功操作所产生的数据</li>
* <li>error 状态下返回一个默认的数据如果存在的话</li>
* <li>loading 状态下返回一个默认的数据如果存在的话</li>
* </pre>
*
* @param defaultData 如果不存在数据则返回 defaultData 所设置的默认数据
* @return Resource 中保存的数据
*/
@Nullable
public T orElse(@Nullable T defaultData) {
if (mData == null) {
return defaultData;
}
return mData;
}
/**
* 获取 Resource 中保存的数据在不同状态下获取的数据具有不同的意义
*
* <pre>
* <li>success 状态下返回一个成功操作所产生的数据</li>
* <li>error 状态下返回一个默认的数据如果存在的话</li>
* <li>loading 状态下返回一个默认的数据如果存在的话</li>
* </pre>
*
* @return Resource 中保存的数据
*/
@Nullable
public T get() {
return mData;
}
public Throwable error() {
return mError;
}
@NonNull
@Override
public String toString() {
return "Resource{" +
"mError=" + mError +
", mStatus=" + mStatus +
", mData=" + mData +
'}';
}
}

@ -1,5 +1,135 @@
package com.android.base.data package com.android.base.data
/**
* @author Ztiany
* Email: ztiany3@gmail.com
* Date : 2018-05-15 16:23
*/
class Resource<T> private constructor(
private val error: Throwable?,
//data or default data
private val data: T?,
private val status: Status
) {
val isSuccess: Boolean
get() = status == Status.SUCCESS
val isNoChange: Boolean
get() = status == Status.NOT_CHANGED
val isLoading: Boolean
get() = status == Status.LOADING
val isError: Boolean
get() = status == Status.ERROR
fun hasData(): Boolean {
return data != null
}
/**
* 获取 Resource 中保存的数据只有在 success 状态并且存在数据时下才能调用此方法否则将抛出异常
*
* @return Resource 中保存的数据
* @throws UnsupportedOperationException success 状态调用此方法
* @throws NullPointerException Resource 中没有保存数据时调用此方法
*/
fun data(): T {
if (isError || isLoading || isNoChange) {
throw UnsupportedOperationException("This method can only be called when the is state success")
}
if (data == null) {
throw NullPointerException("Data is null")
}
return data
}
/**
* 获取 Resource 中保存的数据如果不存在数据则返回 defaultData 所设置的默认数据在不同状态下获取的数据具有不同的意义
*
* * success 状态下返回一个成功操作所产生的数据
* * error 状态下返回一个默认的数据如果存在的话
* * loading 状态下返回一个默认的数据如果存在的话
*
* @param defaultData 如果不存在数据则返回 defaultData 所设置的默认数据
* @return Resource 中保存的数据
*/
fun orElse(defaultData: T?): T? {
return data ?: defaultData
}
/**
* 获取 Resource 中保存的数据在不同状态下获取的数据具有不同的意义
*
* * success 状态下返回一个成功操作所产生的数据
* * error 状态下返回一个默认的数据如果存在的话
* * loading 状态下返回一个默认的数据如果存在的话
*
* @return Resource 中保存的数据
*/
fun get(): T? {
return data
}
fun error(): Throwable {
return error ?: throw NullPointerException("This method can only be called when the state is error")
}
override fun toString(): String {
return "Resource{" +
"mError=" + error +
", mStatus=" + status +
", mData=" + data +
'}'.toString()
}
companion object {
fun <T> success(): Resource<T> {
return Resource(null, null, Status.SUCCESS)
}
fun <T> success(data: T?): Resource<T> {
return Resource(null, data, Status.SUCCESS)
}
fun <T> error(error: Throwable): Resource<T> {
return error(error, null)
}
/**
* 创建一个 error 状态且设置一个默认的数据
*/
fun <T> error(error: Throwable, defaultValue: T?): Resource<T> {
return Resource(error, defaultValue, Status.ERROR)
}
fun <T> loading(): Resource<T> {
return loading(null)
}
/**
* 创建一个 loading 状态且设置一个默认的数据
*/
fun <T> loading(defaultValue: T?): Resource<T> {
return Resource(null, defaultValue, Status.LOADING)
}
/**
* 如果数据源(比如 Repository)缓存了上一次请求的数据然后对其当前请求返回的数据发现数据是一样的可以使用此状态表示
*
* @return Resource
*/
fun <T> noChange(): Resource<T> {
return Resource(null, null, Status.NOT_CHANGED)
}
}
}
/**when in loading*/ /**when in loading*/
inline fun <T> Resource<T>.onLoading(onLoading: () -> Unit): Resource<T> { inline fun <T> Resource<T>.onLoading(onLoading: () -> Unit): Resource<T> {
if (this.isLoading) { if (this.isLoading) {

@ -1,4 +1,4 @@
package com.android.base.data; package com.android.base.data
/** /**
* 用于表示各种状态 * 用于表示各种状态
@ -7,9 +7,9 @@ package com.android.base.data;
* Email: ztiany3@gmail.com * Email: ztiany3@gmail.com
* Date : 2019-02-18 11:49 * Date : 2019-02-18 11:49
*/ */
public enum Status { enum class Status {
LOADING, LOADING,
ERROR, ERROR,
SUCCESS, SUCCESS,
NOT_CHANGED, NOT_CHANGED
} }

@ -30,7 +30,6 @@ public class DisplayConfig {
public static final int ANIM_NONE = 1; public static final int ANIM_NONE = 1;
private DisplayConfig() { private DisplayConfig() {
} }
public static DisplayConfig create() { public static DisplayConfig create() {

@ -1,4 +1,4 @@
package com.android.base.interfaces.adapter; package com.android.base.interfaces;
import android.app.Activity; import android.app.Activity;
import android.app.Application; import android.app.Application;

@ -1,4 +1,4 @@
package com.android.base.interfaces.adapter; package com.android.base.interfaces;
import android.view.View; import android.view.View;

@ -1,4 +1,4 @@
package com.android.base.interfaces.adapter; package com.android.base.interfaces;
import androidx.viewpager.widget.ViewPager; import androidx.viewpager.widget.ViewPager;

@ -1,4 +1,4 @@
package com.android.base.interfaces.adapter; package com.android.base.interfaces;
import android.widget.SeekBar; import android.widget.SeekBar;

@ -1,4 +1,4 @@
package com.android.base.interfaces.adapter; package com.android.base.interfaces;
import com.google.android.material.tabs.TabLayout; import com.google.android.material.tabs.TabLayout;

@ -1,4 +1,4 @@
package com.android.base.interfaces.adapter; package com.android.base.interfaces;
import android.text.Editable; import android.text.Editable;
import android.text.TextWatcher; import android.text.TextWatcher;

@ -1,4 +1,4 @@
package com.android.base.interfaces.adapter; package com.android.base.interfaces;
import android.os.Build; import android.os.Build;
import android.transition.Transition; import android.transition.Transition;

@ -34,8 +34,6 @@ public final class WindowUtils {
*/ */
public static int getDisplayRotation(Activity activity) { public static int getDisplayRotation(Activity activity) {
switch (activity.getWindowManager().getDefaultDisplay().getRotation()) { switch (activity.getWindowManager().getDefaultDisplay().getRotation()) {
case Surface.ROTATION_0:
return 0;
case Surface.ROTATION_90: case Surface.ROTATION_90:
return 90; return 90;
case Surface.ROTATION_180: case Surface.ROTATION_180:
@ -154,5 +152,4 @@ public final class WindowUtils {
return km != null && km.inKeyguardRestrictedInputMode(); return km != null && km.inKeyguardRestrictedInputMode();
} }
} }

@ -0,0 +1,15 @@
package com.android.base.utils.android.views
import android.view.View
import android.widget.ListView
/**ListView 局部刷新*/
fun ListView.updateItemView(position: Int, updater: (itemView: View) -> Unit) {
val firstPos = firstVisiblePosition
val lastPos = lastVisiblePosition
//可见才更新,不可见则在getView()时更新
if (position in firstPos..lastPos) {
val view = getChildAt(position - firstPos)
updater(view)
}
}

@ -11,7 +11,7 @@ import android.widget.EditText
import android.widget.TextView import android.widget.TextView
import androidx.annotation.DrawableRes import androidx.annotation.DrawableRes
import androidx.core.content.ContextCompat import androidx.core.content.ContextCompat
import com.android.base.interfaces.adapter.TextWatcherAdapter import com.android.base.interfaces.TextWatcherAdapter
import com.google.android.material.textfield.TextInputLayout import com.google.android.material.textfield.TextInputLayout
inline fun TextView.textWatcher(init: KTextWatcher.() -> Unit) = addTextChangedListener(KTextWatcher().apply(init)) inline fun TextView.textWatcher(init: KTextWatcher.() -> Unit) = addTextChangedListener(KTextWatcher().apply(init))

@ -131,59 +131,83 @@ fun View.setPaddingBottom(padding: Int) {
this.setPadding(paddingLeft, paddingTop, paddingRight, padding) this.setPadding(paddingLeft, paddingTop, paddingRight, padding)
} }
fun newLayoutParams(width: Int = ViewGroup.MarginLayoutParams.WRAP_CONTENT, height: Int = ViewGroup.MarginLayoutParams.WRAP_CONTENT): ViewGroup.LayoutParams { fun newWWLayoutParams(): ViewGroup.LayoutParams {
return ViewGroup.LayoutParams(width, height) return ViewGroup.LayoutParams(ViewGroup.MarginLayoutParams.WRAP_CONTENT, ViewGroup.MarginLayoutParams.WRAP_CONTENT)
} }
fun newMarginLayoutParams(width: Int = ViewGroup.MarginLayoutParams.WRAP_CONTENT, height: Int = ViewGroup.MarginLayoutParams.WRAP_CONTENT): ViewGroup.MarginLayoutParams { fun newWMLayoutParams(): ViewGroup.LayoutParams {
return ViewGroup.MarginLayoutParams(width, height) return ViewGroup.LayoutParams(ViewGroup.MarginLayoutParams.WRAP_CONTENT, ViewGroup.MarginLayoutParams.MATCH_PARENT)
} }
fun View.setTopMargin(topMargin: Int) { fun newMWLayoutParams(): ViewGroup.LayoutParams {
return ViewGroup.LayoutParams(ViewGroup.MarginLayoutParams.MATCH_PARENT, ViewGroup.MarginLayoutParams.WRAP_CONTENT)
}
fun newMMLayoutParams(): ViewGroup.LayoutParams {
return ViewGroup.LayoutParams(ViewGroup.MarginLayoutParams.MATCH_PARENT, ViewGroup.MarginLayoutParams.MATCH_PARENT)
}
fun newWWMarginLayoutParams(): ViewGroup.MarginLayoutParams {
return ViewGroup.MarginLayoutParams(ViewGroup.MarginLayoutParams.WRAP_CONTENT, ViewGroup.MarginLayoutParams.WRAP_CONTENT)
}
fun newWMMarginLayoutParams(): ViewGroup.MarginLayoutParams {
return ViewGroup.MarginLayoutParams(ViewGroup.MarginLayoutParams.WRAP_CONTENT, ViewGroup.MarginLayoutParams.MATCH_PARENT)
}
fun newMWMarginLayoutParams(): ViewGroup.MarginLayoutParams {
return ViewGroup.MarginLayoutParams(ViewGroup.MarginLayoutParams.MATCH_PARENT, ViewGroup.MarginLayoutParams.WRAP_CONTENT)
}
fun newMMMarginLayoutParams(): ViewGroup.MarginLayoutParams {
return ViewGroup.MarginLayoutParams(ViewGroup.MarginLayoutParams.MATCH_PARENT, ViewGroup.MarginLayoutParams.MATCH_PARENT)
}
fun View.setTopMargin(topMargin: Int, layoutParamsCreator: (() -> ViewGroup.MarginLayoutParams)? = null) {
val params: ViewGroup.LayoutParams? = layoutParams val params: ViewGroup.LayoutParams? = layoutParams
if (params is ViewGroup.MarginLayoutParams) { if (params is ViewGroup.MarginLayoutParams) {
params.topMargin = topMargin params.topMargin = topMargin
} else { } else {
layoutParams = newMarginLayoutParams().apply { layoutParams = layoutParamsCreator?.invoke() ?: newWWMarginLayoutParams().apply {
this.topMargin = topMargin this.topMargin = topMargin
} }
} }
} }
fun View.setBottomMargin(bottomMargin: Int) { fun View.setBottomMargin(bottomMargin: Int, layoutParamsCreator: (() -> ViewGroup.MarginLayoutParams)? = null) {
val params: ViewGroup.LayoutParams? = layoutParams val params: ViewGroup.LayoutParams? = layoutParams
if (params is ViewGroup.MarginLayoutParams) { if (params is ViewGroup.MarginLayoutParams) {
params.bottomMargin = bottomMargin params.bottomMargin = bottomMargin
} else { } else {
layoutParams = newMarginLayoutParams().apply { layoutParams = layoutParamsCreator?.invoke() ?: newWWMarginLayoutParams().apply {
this.bottomMargin = bottomMargin this.bottomMargin = bottomMargin
} }
} }
} }
fun View.setLeftMargin(leftMargin: Int) { fun View.setLeftMargin(leftMargin: Int, layoutParamsCreator: (() -> ViewGroup.MarginLayoutParams)? = null) {
val params: ViewGroup.LayoutParams? = layoutParams val params: ViewGroup.LayoutParams? = layoutParams
if (params is ViewGroup.MarginLayoutParams) { if (params is ViewGroup.MarginLayoutParams) {
params.leftMargin = leftMargin params.leftMargin = leftMargin
} else { } else {
layoutParams = newMarginLayoutParams().apply { layoutParams = layoutParamsCreator?.invoke() ?: newWWMarginLayoutParams().apply {
this.leftMargin = leftMargin this.leftMargin = leftMargin
} }
} }
} }
fun View.setRightMargin(rightMargin: Int) { fun View.setRightMargin(rightMargin: Int, layoutParamsCreator: (() -> ViewGroup.MarginLayoutParams)? = null) {
val params: ViewGroup.LayoutParams? = layoutParams val params: ViewGroup.LayoutParams? = layoutParams
if (params is ViewGroup.MarginLayoutParams) { if (params is ViewGroup.MarginLayoutParams) {
params.rightMargin = rightMargin params.rightMargin = rightMargin
} else { } else {
layoutParams = newMarginLayoutParams().apply { layoutParams = layoutParamsCreator?.invoke() ?: newWWMarginLayoutParams().apply {
this.rightMargin = rightMargin this.rightMargin = rightMargin
} }
} }
} }
fun View.setRightMargins(leftMargin: Int, topMargin: Int, rightMargin: Int, bottomMargin: Int) { fun View.setMargins(leftMargin: Int, topMargin: Int, rightMargin: Int, bottomMargin: Int, layoutParamsCreator: (() -> ViewGroup.MarginLayoutParams)? = null) {
val params: ViewGroup.LayoutParams? = layoutParams val params: ViewGroup.LayoutParams? = layoutParams
if (params is ViewGroup.MarginLayoutParams) { if (params is ViewGroup.MarginLayoutParams) {
params.rightMargin = rightMargin params.rightMargin = rightMargin
@ -191,7 +215,7 @@ fun View.setRightMargins(leftMargin: Int, topMargin: Int, rightMargin: Int, bott
params.bottomMargin = bottomMargin params.bottomMargin = bottomMargin
params.topMargin = topMargin params.topMargin = topMargin
} else { } else {
layoutParams = newMarginLayoutParams().apply { layoutParams = layoutParamsCreator?.invoke() ?: newWWMarginLayoutParams().apply {
this.rightMargin = rightMargin this.rightMargin = rightMargin
this.leftMargin = leftMargin this.leftMargin = leftMargin
this.bottomMargin = bottomMargin this.bottomMargin = bottomMargin

@ -45,7 +45,7 @@ public class ScrollChildSwipeRefreshLayout extends SwipeRefreshLayout {
TypedArray colorsTypeArray = getResources().obtainTypedArray(colorSchemeArrayId); TypedArray colorsTypeArray = getResources().obtainTypedArray(colorSchemeArrayId);
int indexCount = colorsTypeArray.length(); int indexCount = colorsTypeArray.length();
if (indexCount != 0) { if (indexCount != 0) {
int colors[] = new int[indexCount]; int[] colors = new int[indexCount];
for (int i = 0; i < indexCount; i++) { for (int i = 0; i < indexCount; i++) {
colors[i] = colorsTypeArray.getColor(i, Color.BLACK); colors[i] = colorsTypeArray.getColor(i, Color.BLACK);
} }

@ -128,7 +128,6 @@ public class PullToZoomScrollView extends NestedScrollView {
return mContainerView != null && mZoomView != null; return mContainerView != null && mZoomView != null;
} }
@Override @Override
protected boolean overScrollByCompat(int deltaX, int deltaY, protected boolean overScrollByCompat(int deltaX, int deltaY,
int scrollX, int scrollY, int scrollX, int scrollY,

@ -19,7 +19,7 @@ import androidx.viewpager.widget.ViewPager;
* *
* @author Ztiany * @author Ztiany
*/ */
public class ZViewPager extends FrameLayout { public class BannerViewPager extends FrameLayout {
private final ViewPager mViewPager; private final ViewPager mViewPager;
private IPagerNumberView mPageNumberView; private IPagerNumberView mPageNumberView;
@ -32,24 +32,24 @@ public class ZViewPager extends FrameLayout {
private String mTransitionName; private String mTransitionName;
private OnPageClickListener mOnPageClickListener; private OnPageClickListener mOnPageClickListener;
public ZViewPager(Context context) { public BannerViewPager(Context context) {
this(context, null); this(context, null);
} }
public ZViewPager(Context context, AttributeSet attrs) { public BannerViewPager(Context context, AttributeSet attrs) {
this(context, attrs, 0); this(context, attrs, 0);
} }
public ZViewPager(Context context, AttributeSet attrs, int defStyleAttr) { public BannerViewPager(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr); super(context, attrs, defStyleAttr);
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.ZViewPager); TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.BannerViewPager);
/*是否可以缩放*/ /*是否可以缩放*/
mScalable = typedArray.getBoolean(R.styleable.ZViewPager_zvp_scale, false); mScalable = typedArray.getBoolean(R.styleable.BannerViewPager_zvp_scale_enable, false);
/*用于支持5.0的transition动画*/ /*用于支持5.0的transition动画*/
mTransitionName = typedArray.getString(R.styleable.ZViewPager_zvp_item_transition_name); mTransitionName = typedArray.getString(R.styleable.BannerViewPager_zvp_item_transition_name);
int pageId = typedArray.getResourceId(R.styleable.ZViewPager_zvp_pager_number_id, -1); int pageId = typedArray.getResourceId(R.styleable.BannerViewPager_zvp_pager_number_id, -1);
typedArray.recycle(); typedArray.recycle();

@ -7,7 +7,7 @@ package com.android.base.widget.viewpager;
*/ */
public interface IPagerNumberView { public interface IPagerNumberView {
void setViewPager(ZViewPager viewPager); void setViewPager(BannerViewPager viewPager);
void setPageSize(int i); void setPageSize(int i);

@ -83,7 +83,7 @@ class PageNumberView @JvmOverloads constructor(
invalidate() invalidate()
} }
override fun setViewPager(viewPager: ZViewPager) { override fun setViewPager(viewPager: BannerViewPager) {
//no op //no op
} }

@ -1,8 +1,9 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<resources> <resources>
<declare-styleable name="ZViewPager"> <declare-styleable name="BannerViewPager">
<attr name="zvp_scale" format="boolean"/> <!--if pager is scalable, set it to true.-->
<attr name="zvp_scale_enable" format="boolean"/>
<attr name="zvp_pager_number_id" format="reference"/> <attr name="zvp_pager_number_id" format="reference"/>
<attr name="zvp_item_transition_name" format="string|reference"/> <attr name="zvp_item_transition_name" format="string|reference"/>
</declare-styleable> </declare-styleable>

@ -3,7 +3,7 @@ package com.android.base.rx;
import android.app.Application; import android.app.Application;
import android.content.Context; import android.content.Context;
import com.android.base.app.BaseKit; import com.android.base.app.Sword;
/** /**
* @author Ztiany * @author Ztiany
@ -15,7 +15,7 @@ public class TestApplication extends Application {
@Override @Override
protected void attachBaseContext(Context base) { protected void attachBaseContext(Context base) {
super.attachBaseContext(base); super.attachBaseContext(base);
BaseKit.get().getApplicationDelegate().attachBaseContext(base); Sword.get().getApplicationDelegate().attachBaseContext(base);
} }
} }

@ -9,6 +9,8 @@ import com.android.base.adapter.recycler.MultiTypeAdapter;
import com.android.base.app.fragment.BaseListFragment; import com.android.base.app.fragment.BaseListFragment;
import com.android.base.app.ui.AutoPageNumber; import com.android.base.app.ui.AutoPageNumber;
import org.jetbrains.annotations.NotNull;
/** /**
* @author Ztiany * @author Ztiany
* Email: ztiany3@gmail.com * Email: ztiany3@gmail.com
@ -17,7 +19,7 @@ import com.android.base.app.ui.AutoPageNumber;
public class TestListFragment extends BaseListFragment<String> { public class TestListFragment extends BaseListFragment<String> {
@Override @Override
protected void onViewPrepared(@NonNull View view, @Nullable Bundle savedInstanceState) { protected void onViewPrepared(@NotNull @NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewPrepared(view, savedInstanceState); super.onViewPrepared(view, savedInstanceState);
MultiTypeAdapter recyclerAdapter = new MultiTypeAdapter(getContext()); MultiTypeAdapter recyclerAdapter = new MultiTypeAdapter(getContext());
setupLoadMore(recyclerAdapter, new AutoPageNumber(this,recyclerAdapter)); setupLoadMore(recyclerAdapter, new AutoPageNumber(this,recyclerAdapter));

@ -8,6 +8,8 @@ import android.view.View;
import com.android.base.app.fragment.BaseStateFragment; import com.android.base.app.fragment.BaseStateFragment;
import org.jetbrains.annotations.NotNull;
/** /**
* @author Ztiany * @author Ztiany
* Email: 1169654504@qq.com * Email: 1169654504@qq.com
@ -16,7 +18,7 @@ import com.android.base.app.fragment.BaseStateFragment;
public class TestStateFragment extends BaseStateFragment { public class TestStateFragment extends BaseStateFragment {
@Override @Override
public void onAttach(Context context) { public void onAttach(@NotNull Context context) {
super.onAttach(context); super.onAttach(context);
} }
@ -26,7 +28,7 @@ public class TestStateFragment extends BaseStateFragment {
} }
@Override @Override
protected void onViewPrepared(@NonNull View view, @Nullable Bundle savedInstanceState) { protected void onViewPrepared(@NotNull @NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewPrepared(view, savedInstanceState); super.onViewPrepared(view, savedInstanceState);
getStateLayoutConfig(); getStateLayoutConfig();
} }

Loading…
Cancel
Save