-1
我有一個方法,啓動一個if語句onClick以顯示列表數組中的問題,刪除該項目,然後增加一個int以便再次顯示另一個問題onClick。該變量在onCreate之前定義。當我第一次點擊按鈕時,一個隨機項從數組中拉出並顯示出來。如果我再次點擊它,它什麼也不做。什麼?將變量傳遞到其他方法
爪哇
public class Careunderfirequiz extends AppCompatActivity{
int questionsAnswered = 0;
List<String> questions = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
setContentView(R.layout.myLayout);
questions.add("1");
questions.add("2");
questions.add("3");
questions.add("4");
questions.add("5");
questions.add("6");
questions.add("7");
questions.add("8");
questions.add("9");
questions.add("10");
}
public void nextQuestion(View view){
TextView questionsTextView = (TextView)findViewById(R.id.questions);
Button next = (Button)findViewById(R.id.next);
if(questionsAnswered == 0){
Random randomGenerator = new Random();
String randQuestion = questions.get(randomGenerator.nextInt(questions.size()));
questionsTextView.setText(randQuestion);
questions.remove(randQuestion);
questionsAnswered++;
}
if(questionsAnswered == 1){
Random randomGenerator = new Random();
String randQuestion = questions.get(randomGenerator.nextInt(questions.size()));
questionsTextView.setText(randQuestion);
questions.remove(randQuestion);
questionsAnswered++;
}
}
}
的'如果(questionAnwerered == 0)'和'如果(questionAnswered == 1)'似乎沒有必要,因爲你的代碼始終是相同的反正。只要注意questionAnswered == 10,因爲只有10個問題。另外'next'變量沒有被使用,因此無論如何都不需要找到它,因爲按鈕被傳遞給方法,因爲'view'變量總是(假設你設置了android:onclick =「nextQuestion」佈局中的按鈕。 – Ridcully