I am adding TextViews to my layout and I want to keep them when screen orientation changes.
I tried the following code, but it's not working.
public class DetailsActivity extends Activity {
private HashMap<View, TextView> views = new HashMap<View, TextView>();;
@Override
public Object onRetainNonConfigurationInstance() {
return views;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.layout44);
findViewById(R.id.layout44_11).setOnLongClickListener(onLongClickListener);
...
HashMap<View, TextView> data = (HashMap<View, TextView>)this.getLastNonConfigurationInstance();
if (data == null) {
System.out.println("is null");
} else {
for(View key : data.keySet()) {
ViewGroup parent = (ViewGroup) key;
System.out.println(key + " " + data.get(key));
System.out.println(parent.getChildCount());
System.out.println("child: " + parent.getChildAt(0));;
parent.removeView(data.get(key));
data.get(key).setText("asd");
data.get(key).setVisibility(View.VISIBLE);
parent.addView(data.get(key));
}
System.out.println("-------------------");
}
}
private View.OnLongClickListener onLongClickListener = new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
ViewGroup parent = (ViewGroup) v;
if(parent != null) {
TextView tv = new TextView(getApplicationContext());
tv.setText("TextView");
views.put(parent, tv);
parent.addView(tv);
}
return false;
}
};
}
I'm getting exception:
Caused by: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
Why? What am I doing wrong? How to solve it?