Last active
May 31, 2017 22:00
-
-
Save hector6872/8da7dbe1e48d115b6d38b3a70813f328 to your computer and use it in GitHub Desktop.
StateRecyclerView
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?xml version="1.0" encoding="utf-8"?> | |
<resources> | |
<declare-styleable name="StateRecyclerView"> | |
<attr format="reference" | |
name="srv_emptyView"/> | |
</declare-styleable> | |
</resources> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class StateRecyclerView extends RecyclerView { | |
private View emptyView; | |
private int emptyViewId; | |
public StateRecyclerView(Context context) { | |
this(context, null); | |
} | |
public StateRecyclerView(Context context, @Nullable AttributeSet attrs) { | |
this(context, attrs, 0); | |
} | |
public StateRecyclerView(Context context, @Nullable AttributeSet attrs, int defStyle) { | |
super(context, attrs, defStyle); | |
init(attrs); | |
} | |
private void init(@Nullable AttributeSet attrs) { | |
TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.StateRecyclerView); | |
emptyViewId = typedArray.getResourceId(R.styleable.StateRecyclerView_srv_emptyView, 0); | |
typedArray.recycle(); | |
} | |
@Override protected void onAttachedToWindow() { | |
super.onAttachedToWindow(); | |
if (emptyViewId != 0) { | |
emptyView = ((ViewGroup) getParent()).findViewById(emptyViewId); | |
} | |
updateEmptyView(); | |
} | |
@Override public void setAdapter(@Nullable RecyclerView.Adapter adapter) { | |
if (getAdapter() != null) { | |
getAdapter().unregisterAdapterDataObserver(adapterDataObserver); | |
} | |
if (adapter != null) { | |
adapter.registerAdapterDataObserver(adapterDataObserver); | |
} | |
super.setAdapter(adapter); | |
updateEmptyView(); | |
} | |
public void setEmptyView(@NonNull View emptyView) { | |
this.emptyView = emptyView; | |
} | |
private void updateEmptyView() { | |
if (emptyView != null && getAdapter() != null) { | |
boolean showEmptyView = getAdapter().getItemCount() == 0; | |
emptyView.setVisibility(showEmptyView ? VISIBLE : GONE); | |
setVisibility(showEmptyView ? GONE : VISIBLE); | |
} | |
} | |
private final AdapterDataObserver adapterDataObserver = new AdapterDataObserver() { | |
@Override public void onChanged() { | |
super.onChanged(); | |
updateEmptyView(); | |
} | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment