Skip to content

Instantly share code, notes, and snippets.

@hector6872
Last active May 31, 2017 22:00
Show Gist options
  • Save hector6872/8da7dbe1e48d115b6d38b3a70813f328 to your computer and use it in GitHub Desktop.
Save hector6872/8da7dbe1e48d115b6d38b3a70813f328 to your computer and use it in GitHub Desktop.
StateRecyclerView
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="StateRecyclerView">
<attr format="reference"
name="srv_emptyView"/>
</declare-styleable>
</resources>
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