android - 如何初始化 View (ToggleButtons)数组?

标签 android view array-initialization

我在一个 Activity 中有 11 个 ToggleButtons,此刻,在 onCreate 中我声明了一个包含 11 个 ToggleButtons 的数组,我在 onCreate() 中定义它,如下所示:

private static ToggleButton toggleButton[] = new ToggleButton[11];

...

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    toggleButton[0] = (ToggleButton) findViewById(R.id.ToggleButton00);
    toggleButton[1] = (ToggleButton) findViewById(R.id.ToggleButton01);
    toggleButton[2] = (ToggleButton) findViewById(R.id.ToggleButton02);
    toggleButton[3] = (ToggleButton) findViewById(R.id.ToggleButton03);
    toggleButton[4] = (ToggleButton) findViewById(R.id.ToggleButton04);
    toggleButton[5] = (ToggleButton) findViewById(R.id.ToggleButton05);
    toggleButton[6] = (ToggleButton) findViewById(R.id.ToggleButton06);
    toggleButton[7] = (ToggleButton) findViewById(R.id.ToggleButton07);
    toggleButton[8] = (ToggleButton) findViewById(R.id.ToggleButton08);
    toggleButton[9] = (ToggleButton) findViewById(R.id.ToggleButton09);
    toggleButton[10] = (ToggleButton) findViewById(R.id.ToggleButton10);

我确定应该有更好的方法(比如循环),知道吗?你会怎么做?

最佳答案

试试这段代码:

ToggleButton toggleButton[] = new ToggleButton[11];
    int arrayindex = 0;
    int viewcount = 0;
    while (arrayindex < 11) {

        View v = asyncLayout.getChildAt(viewcount);
        if (v instanceof ToggleButton) {

            toggleButton[arrayindex] = (ToggleButton) v;
            arrayindex ++;
        }
        viewcount ++ ;

    }

有任何问题反馈给我

关于android - 如何初始化 View (ToggleButtons)数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21798673/

相关文章:

c - gcc 编译器报告警告,但 a.out 工作顺利,否则

cakephp - 为什么 CakePHP 2.2.4 中的 View 缓存在 View 缓存后会导致空白页?

MySQL- View : definition changes after saving?

android - 循环中的多个膨胀 View

无法使用包含函数指针的结构初始化数组 - 错误 : initializer element is not constant

没有默认构造函数的 C++ 成员数组初始化

android - AsynchTask 中的 progressBar 导致崩溃, "Unable to add window -- token null is not for an application"

android - 防止 Bixby 将我的应用程序旋转为纵向模式

android - 从 native 代码访问 AsyncStorage

RecyclerView显示多个数据时出现java.lang.IndexOutOfBoundsException