简体   繁体   English

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

[英]Android - Programmatically adding button, setting ID crashes

I am programmatically adding x amount of buttons to my view depending on a config loaded (lets just use 10 for an example).我根据加载的配置以编程方式将 x 数量的按钮添加到我的视图中(例如,仅使用 10 个)。 I create the 10 just fine, and it works when I don't set an ID, or when I use Androids generateId() function, but I want to use my iterator (i) to set the id, so that each value of the iteration matches the button it creates我创建了 10 就好了,当我没有设置 ID 或者当我使用 Androids generateId() 函数时它可以工作,但是我想使用我的迭代器 (i) 来设置 id,这样每个值迭代匹配它创建的按钮

ie IE

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

I want this so that when I switch fragments, it saves the buttons and I don't recreate them with onCreate.我想要这样,当我切换片段时,它会保存按钮并且我不会使用 onCreate 重新创建它们。 As it stands, I get this error:就目前而言,我收到此错误:

 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)

You can use generateViewId within your for and create a method to get your buttons from an ArrayList.您可以在 for 中使用generateViewId并创建一个方法来从 ArrayList 中获取您的按钮。

Try this:尝试这个:

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

}

Or just create an ArrayList of buttons...或者只是创建一个按钮的 ArrayList ......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM