我需要做一個數學測驗。這裏是工作流程:Android數學測驗(線程操作)
點擊按鈕(開始)我需要顯示一個問題,例如5 + 5,在屏幕上停留2秒鐘,然後顯示對話框詢問前一次操作的結果。我需要重複說明例如5次。最後,我需要向用戶展示正確答案的數量。
我有Java的經驗,但我是Android新手。我已閱讀過有關Android線程的各種文章和示例,但尚未找到此工作流程的解決方案。
據我所知,我不能阻止或暫停主/ UI線程,但問題是我應該重複例如5次和每次之後(2秒後),我應該暫停活動以顯示對話框,然後再回到顯示另一個問題。
在此先感謝!編輯: 這是我現在的代碼。該號碼顯示在屏幕上,2秒鐘後顯示提示對話框,要求輸入該號碼。但問題是,應用程序不會等待用戶輸入,而是繼續顯示新的隨機數,每2秒打開一個新的警報對話框。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_questions);
tv = (TextView) findViewById(R.id.questionText);
handler = new Handler();
Runnable r = new Runnable() {
public void run() {
tv.setText(String.valueOf(rand.nextInt(50) + 1));
createDialog();
handler.postDelayed(this, 2000);
}
};
handler.postDelayed(r, 2000);
}
protected void createDialog() {
LayoutInflater li = LayoutInflater.from(context);
View promptsView = li.inflate(R.layout.activity_answer_dialog, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
// set prompts.xml to alertdialog builder
alertDialogBuilder.setView(promptsView);
final EditText userInput = (EditText) promptsView.findViewById(R.id.editTextDialogUserInput);
// set dialog message
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// get user input and set it to result
// edit text
result.setText(userInput.getText());
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
PS。此外,我試圖創建對話框獨立的活動,並將此行的體現:
android:theme="@android:style/Theme.Dialog"
,但同樣的事情發生。