I have some problems with Android Activity’s orientation changes.
I have a game and some flying balloons on it. Balloon (ImageViews) are created dynamically, so they are flying. But when I change device orientation (to port or land) activity is re-creating and my balloons are disappearing. Same thing happens when I move to the next activity and then go back to my balloons activity.
Is there any way to “save” my dynamically created balloons (and it’s position and other properties) on my activity
I also tried getLastNonConfigurationInstance() / onRetainNonConfigurationInstance() but it seems to me that it’s work with data, not View elements (may be because parent of these views is previous activity)
public class Singleton {
private static final Singleton instance = new Singleton();
private Button btn;
private Singleton() {
}
public static Singleton getInstance() {
return instance;
}
public void createBtn(Context context, LinearLayout layout) {
if (btn == null) {
btn = new Button(context);
layout.addView(btn);
}
}
}
public class TestActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Singleton s = Singleton.getInstance();
s.createBtn(this, ((LinearLayout) findViewById(R.id.baseLayout)));
}
}
Button will not appear at second onCreate (on change orientation) (I think the problem is that Button’s Context is previous Activity)
Updated code:
public class Singleton {
private static final Singleton instance = new Singleton();
private Button btn;
private SparseArray<Parcelable> container;
private Singleton() {
}
public static Singleton getInstance() {
return instance;
}
public void createBtn(Context context, LinearLayout layout) {
if (btn == null) {
btn = new Button(context);
layout.addView(btn);
btn.setText("Hello");
saveBtn();
} else if (container != null){
btn = new Button(context);
btn.restoreHierarchyState(container);
layout.addView(btn);
}
}
public void saveBtn() {
container = new SparseArray<Parcelable>();
btn.saveHierarchyState(container);
}
}
I think that on new Button should appear “Hello” text, but it’s doesn’t happen. Whats wrong?
Override the
onSaveInstanceState()callback in your activity. Save all the data to the bundle you receive in this method. InonCreateof your activity check thesavedInstancebundle for null. If its not null, read back and apply the data to your views.Update
Don’t check for null in
createBtnmethod.Update 2
Make the
containervariable static. I think you are losing the values when activity restarts.