如何获取片段中所有视图的列表?
How to get a list of all views in a fragment?
我想获得主 Fragment
内所有视图的列表,以便我可以在 for 循环中遍历它们。也许是这样的:
for (View v : fragmentViews) {
好的,片段有方法 getView() :
Get the root view for the fragment's layout (the one returned by
{@link #onCreateView}), if provided. @return The fragment's root view,
or null if it has no layout.
您可以这样做:
try {
ViewGroup rootView = (ViewGroup) getView();
int childViewCount = rootView.getChildCount();
for (int i=0; i<childViewCount;i++){
View workWithMe = rootView.getChildAt(i);
}
} catch (ClassCastException e){
//Not a viewGroup here
} catch (NullPointerException e){
//Root view is null
}
在你的 onCreateView
中以通常的方式膨胀你的片段:-
View rootView = inflater.inflate(R.layout.my_fragment, container, false);
循环浏览片段的视图:
ViewGroup container = (ViewGroup) rootView;
int count = container.getChildCount();
for (int i = 0; i < count; i++) {
View v = container.getChildAt(i);
// perform action on this view
}
我想获得主 Fragment
内所有视图的列表,以便我可以在 for 循环中遍历它们。也许是这样的:
for (View v : fragmentViews) {
好的,片段有方法 getView() :
Get the root view for the fragment's layout (the one returned by {@link #onCreateView}), if provided. @return The fragment's root view, or null if it has no layout.
您可以这样做:
try {
ViewGroup rootView = (ViewGroup) getView();
int childViewCount = rootView.getChildCount();
for (int i=0; i<childViewCount;i++){
View workWithMe = rootView.getChildAt(i);
}
} catch (ClassCastException e){
//Not a viewGroup here
} catch (NullPointerException e){
//Root view is null
}
在你的 onCreateView
中以通常的方式膨胀你的片段:-
View rootView = inflater.inflate(R.layout.my_fragment, container, false);
循环浏览片段的视图:
ViewGroup container = (ViewGroup) rootView;
int count = container.getChildCount();
for (int i = 0; i < count; i++) {
View v = container.getChildAt(i);
// perform action on this view
}