1. 在style中:
<declare-styleable name="SmartRecyclerView">
<attr name="smr_empty_layout" format="reference" />
<attr name="smr_error_layout" format="reference" />
</declare-styleable>
2. 在自定义控件SmartRecyclerView中:
public SmartRecyclerView(@NonNull Context context, @Nullable AttributeSet attrs) {
...
TypedArray ta = mContext.obtainStyledAttributes(attrs, R.styleable.SmartRecyclerView);
mEmptyLayoutId = ta.getResourceId(R.styleable.SmartRecyclerView_smr_empty_layout, -1);
mErrorLayoutId = ta.getResourceId(R.styleable.SmartRecyclerView_smr_error_layout, -1);
ta.recycle();
}
...
public void setLayoutManager(RecyclerView.LayoutManager layout) {
mRecyclerView.setLayoutManager(layout);
if (layout != null) {
//inflate之前必须先设定recyclerView的LayoutManager
if (mEmptyLayoutId > -1) {
mEmptyView = mInflater.inflate(mEmptyLayoutId, mRecyclerView, false);
}
if (mErrorLayoutId > -1) {
mErrorView = mInflater.inflate(mErrorLayoutId, mRecyclerView, false);
}
}
}
3. 在布局文件中使用:
<com.xxx.view.SmartRecyclerView
android:id="@+id/smart_refresh_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
rcv:smr_empty_layout="@layout/empty_layout"
rcv:smr_error_layout="@layout/error_layout" />