In RecyclerView
, I want to set an empty view to be shown when the adapter is empty. Is there an equivalent of ListView.setEmptyView()?
You can just paint the text on the RecyclerView
when it's empty. The following custom subclass supports empty
, failed
, loading
, and offline
modes. For successful compilation add recyclerView_stateText
color to your resources.
/**
* {@code RecyclerView} that supports loading and empty states.
*/
public final class SupportRecyclerView extends RecyclerView
{
public enum State
{
NORMAL,
LOADING,
EMPTY,
FAILED,
OFFLINE
}
public SupportRecyclerView(@NonNull Context context)
{
super(context);
setUp(context);
}
public SupportRecyclerView(@NonNull Context context, @Nullable AttributeSet attrs)
{
super(context, attrs);
setUp(context);
}
public SupportRecyclerView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyle)
{
super(context, attrs, defStyle);
setUp(context);
}
private Paint textPaint;
private Rect textBounds;
private PointF textOrigin;
private void setUp(Context c)
{
textPaint = new Paint();
textPaint.setAntiAlias(true);
textPaint.setColor(ContextCompat.getColor(c, R.color.recyclerView_stateText));
textBounds = new Rect();
textOrigin = new PointF();
}
private State state;
public State state()
{
return state;
}
public void setState(State newState)
{
state = newState;
calculateLayout(getWidth(), getHeight());
invalidate();
}
private String loadingText = "Loading...";
public void setLoadingText(@StringRes int resId)
{
loadingText = getResources().getString(resId);
}
private String emptyText = "Empty";
public void setEmptyText(@StringRes int resId)
{
emptyText = getResources().getString(resId);
}
private String failedText = "Failed";
public void setFailedText(@StringRes int resId)
{
failedText = getResources().getString(resId);
}
private String offlineText = "Offline";
public void setOfflineText(@StringRes int resId)
{
offlineText = getResources().getString(resId);
}
@Override
public void onDraw(Canvas canvas)
{
super.onDraw(canvas);
String s = stringForCurrentState();
if (s == null)
return;
canvas.drawText(s, textOrigin.x, textOrigin.y, textPaint);
}
private void calculateLayout(int w, int h)
{
String s = stringForCurrentState();
if (s == null)
return;
textPaint.setTextSize(.1f * w);
textPaint.getTextBounds(s, 0, s.length(), textBounds);
textOrigin.set(
w / 2f - textBounds.width() / 2f - textBounds.left,
h / 2f - textBounds.height() / 2f - textBounds.top);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh)
{
super.onSizeChanged(w, h, oldw, oldh);
calculateLayout(w, h);
}
private String stringForCurrentState()
{
if (state == State.EMPTY)
return emptyText;
else if (state == State.LOADING)
return loadingText;
else if (state == State.FAILED)
return failedText;
else if (state == State.OFFLINE)
return offlineText;
else
return null;
}
}