Skip to content

Instantly share code, notes, and snippets.

@BCsl
Created September 20, 2016 03:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BCsl/2429407a6ab18e5524f8c8ce05e7112d to your computer and use it in GitHub Desktop.
Save BCsl/2429407a6ab18e5524f8c8ce05e7112d to your computer and use it in GitHub Desktop.
Easy using ViewStub to lazy inflate layout
/**
* Created by chensuilun on 16-9-20.
*/
public abstract class ViewStubWidget {
private ViewGroup mParent;
private int mStubId;
private ViewStub mViewStub;
private View mRoot;
public ViewStubWidget(ViewGroup parent, int stubId) {
mParent = parent;
mStubId = stubId;
}
/**
* 初始化控件
*/
public void inflateWidget() {
if (!isInflate()) {
if (mViewStub == null) {
mViewStub = (ViewStub) mParent.findViewById(mStubId);
}
mViewStub.inflate();
mViewStub.setOnInflateListener(new ViewStub.OnInflateListener() {
@Override
public void onInflate(ViewStub stub, View inflated) {
mViewStub.setOnInflateListener(null);
mRoot = inflated;
initView(mParent, mRoot);
}
});
}
}
/**
* @param parent
* @param self
*/
public abstract void initView(ViewGroup parent, View self);
/**
* @return
*/
public boolean isInflate() {
return mRoot != null;
}
public boolean isShowing() {
return mViewStub != null && mRoot != null && mRoot.isShown();
}
/**
* 显示控件
*/
public void show() {
inflateWidget();
if (mRoot != null && !mRoot.isShown()) {
mRoot.setVisibility(View.VISIBLE);
}
}
/**
* 隐藏控件
*/
public void hide() {
if (mRoot != null && mRoot.isShown()) {
mRoot.setVisibility(View.GONE);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment