问题:当用户开始游戏时,他有6个单词可供选择,这6个单词是从列表中随机选择的。但是,每次用户关闭此活动然后再次重新打开它时,会出现一组不同的六个单词。
这就是我试图解决这个问题的方法:
public class GameActivity extends Activity {
protected static ArrayList<String> mSavedList;
protected TextView word1;
protected LinkedList<String> mCopy;
protected TextView word2;
/// all the way to word6
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
if (savedInstanceState != null) {
mSavedList = savedInstanceState.getStringArrayList("savedList");
word1 = (TextView) findViewById(R.id.word1);
word1.setText(mSavedList.get(1));
word2 = (TextView) findViewById(R.id.word2);
word2.setText(mSavedList.get(2));
//up until word6
}
else {
//take the list of all the words in the LinkedList mCopy,
randomize it, and pick the first six.
}
}// end of onCreate method
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
mSavedList = new ArrayList<String>(mCopy.subList(1, 7));
savedInstanceState.putStringArrayList("savedList", mSavedList);
super.onSaveInstanceState(savedInstanceState);
}
当我运行代码时,我的应用程序不会崩溃,它只是继续表现得好像没有创建捆绑包。我不知道我做错了什么。
答案 0 :(得分:0)
嗨,我编辑代码,请看下面的内容
mSavedList = new ArrayList(mCopy.subList(1,7));
如果savedInstanceState为null,则只能生成随机数。 还有一个从arrray列表中删除静态使其正常
public class GameActivity extends Activity {
protected ArrayList<String> mSavedList;
protected TextView word1;
protected LinkedList<String> mCopy;
protected TextView word2;
/// all the way to word6
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
if (savedInstanceState != null) {
mSavedList = savedInstanceState.getStringArrayList("savedList");
word1 = (TextView) findViewById(R.id.word1);
word1.setText(mSavedList.get(1));
word2 = (TextView) findViewById(R.id.word2);
word2.setText(mSavedList.get(2));
//up until word6
}
else {
//take the list of all the words in the LinkedList mCopy,
randomize it, and pick the first six.
mSavedList = new ArrayList<String>(mCopy.subList(1, 7));
}
}// end of onCreate method
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putStringArrayList("savedList", mSavedList);
super.onSaveInstanceState(savedInstanceState);
}