我正在创建一些带按钮的EditTexts,我创建了一个实现OnClickListener的类,我想在屏幕旋转后保存那些EditTexts,但它们总是消失。我知道
轮换活动被销毁并再次创建
我无法在Bundle中保存EditText,因为它没有实现Parcelable或类似的东西
所以我尝试用onSaveInstanceState(Bundle savedInstanceState)
至少保存他们身上的ID和文字
但它没有被调用,因为它不在主类中,而是在另一个名为ViewControl的调用中。我需要保存一些私有变量(text和id),这就是为什么我在我的类中有这个方法的原因。我试图从另一个onSaveInstance中调用这个方法,这个方法主要但是没有运气。你能告诉我一些简单的方法来编程创建一个在另一个下面的EditTexts并在屏幕旋转后保持它们吗?我真的找不到任何简单的方法......
主要课程
public class MainActivity extends Activity {
private ViewControl vc;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
vc = new ViewControl(this);
}
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
vc.onSaveInstanceState(savedInstanceState);
}
ViewControl类
import java.util.ArrayList;
public class ViewControl extends Activity implements View.OnClickListener{
private Button btn;
private RelativeLayout rl;
private Activity act;
private ArrayList<Integer> id;
private ArrayList<String> userpath;
private int lastId;
public ViewControl(Activity activity) {
this.act = activity;
this.id = new ArrayList<Integer>();
this.userpath = new ArrayList<String>();
this.rl = (RelativeLayout)act.findViewById(R.id.layout);
this.btn = (Button)act.findViewById(R.id.btn);
this.id.add(Integer.valueOf(R.id.btn));
this.btn.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if(id.size() != 1)
lastId = id.get(id.size() - 1);
else
lastId = R.id.btn;
RelativeLayout.LayoutParams par = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
par.addRule(RelativeLayout.BELOW, lastId);
EditText et = new EditText(act);
et.setId(++lastId);
id.add(Integer.valueOf(lastId));
et.setText(Integer.toString(lastId));
rl.addView(et, par);
lastId = et.getId();
}
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putIntegerArrayList("ids", id);
savedInstanceState.putStringArrayList("userpaths", userpath);
savedInstanceState.putInt("lastId", lastId);
Toast.makeText(act, "Onsave", Toast.LENGTH_LONG).show();
}
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
this.id = savedInstanceState.getIntegerArrayList("ids");
this.userpath = savedInstanceState.getStringArrayList("userpaths");
this.lastId = savedInstanceState.getInt("lastId");
Toast.makeText(act, "Onrestore", Toast.LENGTH_LONG).show();
for(int i = 0; i < id.size(); i++)
{
RelativeLayout.LayoutParams par = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
par.addRule(RelativeLayout.BELOW, lastId);
EditText et = new EditText(act);
et.setId(this.id.get(i));
}
}
}
答案 0 :(得分:0)
调用的顺序错误(MainActivity
和ViewControl
)。首先,您应该添加数据,然后将Bundle
传递给super
进行保存(请参阅文档here)。 (您的onRestoreInstanceState
没问题)