Android - 以编程方式添加按钮,设置ID崩溃

时间:2017-01-25 15:54:37

标签: java android dynamic error-handling

我正在以编程方式在我的视图中添加x个按钮,具体取决于加载的配置(让我们只使用10作为示例)。我创建10就好了,当我没有设置ID,或者当我使用Androids generateId()函数时,它工作,但我想使用我的迭代器(i)来设置id,以便每个值迭代次数匹配它创建的按钮

(for i=0; i<10; i++)
{
     button.setId(i);
 }

我希望这样,当我切换片段时,它会保存按钮,而我不会使用onCreate重新创建它们。就目前而言,我收到了这个错误:

 01-25 17:46:18.197  13236-13236/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.ClassCastException: android.view.AbsSavedState$1 cannot be cast to android.widget.CompoundButton$SavedState
        at android.widget.CompoundButton.onRestoreInstanceState(CompoundButton.java:379)

1 个答案:

答案 0 :(得分:1)

您可以在for中使用generateViewId并创建一个方法从ArrayList获取按钮。

试试这个:

public class YourClass {

    public ArrayList<Integer> ids = new ArrayList<>();

    public void generateButtons(){
        for (int i = 0; i< 10; i++) {
            ids.add(View.generateViewId());
            // your code to create the button
            button.setId(ids.get(i));
        }
    }

    public Button getButton(int index){
        return (Button) findViewById(ids.get(index));
    }

}

或者只是创建一个按钮的ArrayList ...