gpt4 book ai didi

安卓 fragment : How to loop through fragment controls

转载 作者:行者123 更新时间:2023-11-29 16:08:46 25 4
gpt4 key购买 nike

如何使 Fragment 中的所有 Spinner 都可聚焦?

在我的布局的 XML 中设置 android:focusableInTouchModeandroid:focusable 没有效果。

更一般地说,我在遍历 Fragment 的控件并查找特定类型的所有控件(例如所有 Spinners 或所有 EditTexts)时遇到问题。

最佳答案

这对我来说非常棘手,所以我想我会在这里发布我的解决方案。这解决了一个特定的问题(如何使微调器可聚焦),但也解决了一个更普遍的问题(如何循环访问 fragment 中的控件。

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();
}
}
});
}
}


}

关于安卓 fragment : How to loop through fragment controls,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15390560/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com