如何使我的片段中的所有Spinners都可以聚焦?Android片段:如何通过片段控件循环
设置android:focusableInTouchMode
和android:focusable
在我的布局的XML是没有效果的。
更一般地说,我无法循环浏览我的Fragment控件并找到特定类型的所有控件,例如所有Spinners或所有EditTexts。
如何使我的片段中的所有Spinners都可以聚焦?Android片段:如何通过片段控件循环
设置android:focusableInTouchMode
和android:focusable
在我的布局的XML是没有效果的。
更一般地说,我无法循环浏览我的Fragment控件并找到特定类型的所有控件,例如所有Spinners或所有EditTexts。
这对我来说非常棘手,所以我想我会在这里发布我的解决方案。这解决了一个特别的问题(如何使纺纱厂可调焦),而且还解决了更一般的问题(如何通过控制回路中的片段。
public class MyFragment extends Fragment {
private static ArrayList<Spinner> spinners = new ArrayList<Spinner>();
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// inflate the layout
View layout = inflater.inflate(R.layout.my_fragment_xml, container, false);
// cast our newly inflated layout to a ViewGroup so we can
// enable looping through its children
set_spinners((ViewGroup)layout);
// now we can make them focusable
make_spinners_focusable();
return layout;
}
//find all spinners and add them to our static array
private void set_spinners(ViewGroup container) {
int count = container.getChildCount();
for (int i = 0; i < count; i++) {
View v = container.getChildAt(i);
if (v instanceof Spinner) {
spinners.add((Spinner) v);
} else if (v instanceof ViewGroup) {
//recurse through children
set_spinners((ViewGroup) v);
}
}
}
//make all spinners in this fragment focusable
//we are forced to do this in code
private void make_spinners_focusable() {
for (Spinner s : spinners) {
s.setFocusable(true);
s.setFocusableInTouchMode(true);
s.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
v.performClick();
}
}
});
}
}
}
与set_spinners()
所选择的答案,如果有嵌套布局中不起作用。活动getChildCount()
只给出了第一级的孩子的最好使用getAllChildrenBFS
从这个answer: