我正在将 TextViews 添加到我的布局中,并且我想在屏幕方向更改时保留它们。
我尝试了以下代码,但它不起作用。
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;
}
};
}
我遇到了异常:
引起:java.lang.IllegalStateException:指定的孩子已经有一个父母。您必须首先在孩子的父母上调用 removeView()。
为什么?我究竟做错了什么?如何解决?