测验中的进度条(Android Studio)

时间:2016-05-20 10:01:30

标签: java android android-studio

我正在创建一个问答游戏,我添加了进度条。我希望进度条给出10秒钟来回答每个问题,如果时间用完,它应该显示结果屏幕。 我该怎么做?

  

package com.example.sqz;




import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import java.util.List;
import java.util.concurrent.TimeUnit;


public class QuestionActivity extends Activity {
List<Question> quesList;
int score = 0;
int qid = 0;


Question currentQuestion;
TextView txtQuestion, times, scored;
Button Answer1, Answer2, Answer3, Answer4;
QuizHelper db;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //level difficulty
    int level;
    level = getIntent().getIntExtra("level",-1);  //get LEVEL from intent. If no LEVEL in intent, LEVEL=-1.

    //if level not equal "-1" (so level was in intent), get questions for this level from database
    if(level!=-1)   {
        db=new QuizHelper(this);
        quesList=db.getAllQuestionsByLevel(level);
    }


    currentQuestion = quesList.get(qid); //  current question


    txtQuestion = (TextView) findViewById(R.id.txtQuestion); // textview to view the question



    // the four answer buttons
    Answer1 = (Button) findViewById(R.id.btnAnswer1);
    Answer2 = (Button) findViewById(R.id.btnAnswer2);
    Answer3 = (Button) findViewById(R.id.btnAnswer3);
    Answer4 = (Button) findViewById(R.id.btnAnswer4);


    // text view to show score
    scored = (TextView) findViewById(R.id.score);

    // textview for timer
    times = (TextView) findViewById(R.id.timers);


    // method to set the game
    setQuestionView();
    times.setText(R.string.timertext);

    final ProgressBar mProgressBar;
    CountDownTimer mCountDownTimer;
    final int[] i = {0};

    mProgressBar=(ProgressBar)findViewById(R.id.progressbar);
    mProgressBar.setProgress(i[0]);
    mCountDownTimer=new CountDownTimer(5000,1000) {

        @Override
        public void onTick(long millisUntilFinished) {
            Log.v("Log_tag", "Tick of Progress" + i[0] + millisUntilFinished);
            i[0]++;
            mProgressBar.setProgress(i[0]);

        }

        @Override
        public void onFinish() {
            //Do what you want
            i[0]++;
            mProgressBar.setProgress(i[0]);
        }
    };
    mCountDownTimer.start();;




    // button click listeners
    Answer1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) { // method to check if the answer is correct

            getAnswer(Answer1.getText().toString());
        }
    });

    Answer2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            getAnswer(Answer2.getText().toString());
        }
    });

    Answer3.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            getAnswer(Answer3.getText().toString());
        }
    });
    Answer4.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            getAnswer(Answer4.getText().toString());
        }
    });
}

public void getAnswer(String AnswerString) {
    if (currentQuestion.getANSWER().equals(AnswerString)) {


        score = score + 5; // increase the sore by 5 if the answer is correct
        scored.setText("Score : " + score); // set text of textview to score

    } else { //load the result screen if wrong answer is selected

        Intent intent;
        intent = new Intent(QuestionActivity.this,
                ResultActivity.class);


        Bundle b;
        b = new Bundle();
        b.putInt("score", score);
        intent.putExtras(b); // Put your score to your next
        startActivity(intent); // starts the activity
        finish();
    }
    if (qid < 20) { // 20 questions for each level

        // until the questions are over do this
        currentQuestion = quesList.get(qid);
        setQuestionView();
    } else {

        // once the questions are finished show results screen
        Intent intent = new Intent(QuestionActivity.this,
                ResultActivity.class);
        Bundle b = new Bundle();
        b.putInt("score", score); // Your score
        intent.putExtras(b); // Put your score to your next
        startActivity(intent);
        finish();
    }


}



public class CounterClass extends CountDownTimer {

    public CounterClass(long millisInFuture, long countDownInterval) {
        super(millisInFuture, countDownInterval);

    }


    @Override
    public void onFinish() {
        times.setText("Time is up");

    }

    @Override
    public void onTick(long millisUntilFinished) {


        long millis = millisUntilFinished;
        String hms = String.format(
                "%02d:%02d:%02d",
                TimeUnit.MILLISECONDS.toHours(millis),
                TimeUnit.MILLISECONDS.toMinutes(millis)
                        - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS
                        .toHours(millis)),
                TimeUnit.MILLISECONDS.toSeconds(millis)
                        - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS
                        .toMinutes(millis)));
        System.out.println(hms);
        times.setText(hms);
    }


}

private void setQuestionView() {

    // the method which will put questions and answers together
    txtQuestion.setText(currentQuestion.getQUESTION());
    Answer1.setText(currentQuestion.getA1());
    Answer2.setText(currentQuestion.getA2());
    Answer3.setText(currentQuestion.getA3());
    Answer4.setText(currentQuestion.getA4());

    qid++;

}


}

1 个答案:

答案 0 :(得分:1)

您可以使用正在运行的Thread或AsyncTask 1)对于正在运行的线程, 在您的活动xml中,

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ProgressBar
    style="@android:style/Widget.ProgressBar.Horizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="10dp"
    android:progress="100"
    android:id="@+id/progress"/>
</LinearLayout>

在您的活动中

public class TestActivity extends AppCompatActivity{

private ProgressBar moveBar;
private int count;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_test);

    moveBar = (ProgressBar)findViewById(R.id.progress);
    moveBar.setProgress(100);

    startProgress();

}

private void startProgress() {

    Thread sleep = new Thread(new Runnable() {
        @Override
        public void run() {
            for(count =10; count >=0; count --) {

                try {
                    Thread.sleep(1000); //every 1sec

                    // here you check for the result if correct
                    //i use count == 5 as an example, uncomment to see
                    /*if(count == 5){
                        count = 10;
                        moveBar.setProgress(100);
                        startProgress();
                        break;
                    }*/
                }catch (Exception i){
                    i.printStackTrace();
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        moveBar.setProgress(10 * count);
                        Log.e("Count", " " + count);


                        if(count == 0){
                            Toast.makeText(getApplicationContext(),
                                    "Result screen", Toast.LENGTH_SHORT).show();
                        }
                    }
                });

            }
        }
    });sleep.start();
}
}

2)对于AsyncTask,请使用这些链接指导您 http://www.compiletimeerror.com/2013/01/why-and-how-to-use-asynctask.html#.Vz7rW3yrS6k

http://www.vogella.com/tutorials/AndroidBackgroundProcessing/article.html

https://androidresearch.wordpress.com/2012/03/17/understanding-asynctask-once-and-forever/