1

I am programmatically adding x amount of buttons to my view depending on a config loaded (lets just use 10 for an example). 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

i.e.

(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. 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)
  • It might help http://stackoverflow.com/questions/28961176/java-lang-classcastexception-android-view-abssavedstate1-cannot-be-cast-to-and – Raghavendra Jan 25 '17 at 15:58
  • Why dont you use `button.setTag("yourID")` – Tyrmos Jan 25 '17 at 16:01
  • Well if I give it an ID, doesn't it save the fact that it's been created in the Saved Bundle? Otherwise I'm just creating 10 new buttons each time I switch back to the fragment. – Michael Stevens Jan 25 '17 at 16:06
  • I think your problem would be settings same id to another views. Make sure your activity have configChanges to spesific cases in manifest and handle your solution in onConfigChange. – Emre Aktürk Jan 25 '17 at 16:15

1 Answers1

1

You can use generateViewId within your for and create a method to get your buttons from an 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...

Adson Leal
  • 31
  • 3
  • Thanks...I actually just ended up having my unique ID start at 400 and iterate through the amount of buttons, I guess there was a conflict of IDs between another id/view....lol. I spent quite a bit of time looking into the casting and what not on other posts, and I guess I just wanted a corresponding id between button and uniqueID but this will do. Thanks! – Michael Stevens Jan 25 '17 at 16:25