Last active
June 6, 2016 06:49
-
-
Save tuanchauict/222109bf1ff8960a53fbd2489db045ec to your computer and use it in GitHub Desktop.
Shortcut way for finding a view that is located inside layout of an ViewStub on Android.
This file contains 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
private SparseArray<View> mViewStubSparseArray; | |
/** | |
* Find view inside ViewStub layout | |
* | |
* @param stubId | |
* @param viewId | |
* @param <T> | |
* @return | |
*/ | |
public <T extends View> T findLazyViewById(@IdRes int stubId, @IdRes int viewId) { | |
if (mViewStubSparseArray == null) { | |
mViewStubSparseArray = new SparseArray<>(); | |
} | |
View container = getView(); | |
if (container == null) { | |
return null; | |
} | |
View parent = mViewStubSparseArray.get(stubId); | |
if (parent == null) { | |
ViewStub stub = (ViewStub) container.findViewById(stubId); | |
if (stub == null) { | |
return null; | |
} | |
parent = stub.inflate(); | |
mViewStubSparseArray.put(stubId, parent); | |
if (parent == null) { | |
return null; | |
} | |
} | |
return (T) parent.findViewById(viewId); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment