【问题标题】:Android Quiz Application Count Down TimerAndroid 测验应用程序倒数计时器
【发布时间】:2016-01-06 14:14:22
【问题描述】:

大家好,我仍在做我的顶点项目 我需要一个代码,当活动开始时,计时器也开始,当它结束时,它进入结果活动要实现该倒计时,我们将非常感谢您的帮助

package org.intercode.lifeatceu;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.provider.MediaStore;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import java.util.HashSet;
import java.util.Random;

public class levelone extends AppCompatActivity {
TextView tv1, tvCred, tvQuestion, tvTime;
Button btNext;
RadioButton rb1, rb2;
RadioGroup rg;

String questions [] = {"Ma. Cristina D. Padolina is CEU's President", "Carlito B. Olaer is the V.P of CEU", "CEU's VISION is to sting every enemy", "One of CEU's Mission is to promote creative and scholarly academic"};
String answer [] = {"True", "False", "False", "True"};
HashSet numbers = new HashSet();


int flag = 0;
Random rnd = new Random();
int flag2 = 0 ;
int score = 0;
int correct = 0;
int wrong = 0;
int coins = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_levelone);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    Intent inquiz = getIntent();
   final int credit = inquiz.getIntExtra("passedCredits", 0);
    String TotalCoins = String.valueOf(credit);



    tv1 = (TextView) findViewById(R.id.tv1);
    tvCred = (TextView) findViewById(R.id.tvCred);
    tvQuestion = (TextView) findViewById(R.id.tvQuestion);
    tvTime = (TextView) findViewById(R.id.tvTime);
    rb1 = (RadioButton) findViewById(R.id.rb1);
    rb2 = (RadioButton) findViewById(R.id.rb2);
    rg = (RadioGroup) findViewById(R.id.rg);
    btNext = (Button) findViewById(R.id.btNext);
    flag2 = rnd.nextInt(4);
    numbers.add(flag2);



    tvQuestion.setText(questions[flag2]);
    tvCred.setText(TotalCoins);

    btNext.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            RadioButton uans = (RadioButton) findViewById(rg.getCheckedRadioButtonId());
            String ansText = uans.getText().toString();
            if (ansText.equalsIgnoreCase(answer[flag2]))
            {
                while (numbers.contains(flag2))
                {
                    flag2 = rnd.nextInt(4);
                }
                correct++;
                coins++;

            }
            else
            {
                wrong++;
            }
            flag++;
            flag2 = rnd.nextInt(4);
            if (flag < questions.length)
            {
                tvQuestion.setText(questions[flag2]);
            }
            else
            {
                score = correct;
                Intent in = new Intent(getApplicationContext(), Results.class);
                in.putExtra("passedCredits", credit);
                in.putExtra("passedWrong", wrong);
                in.putExtra("passedCorrect", correct);
                in.putExtra("passedCoins", coins);
                startActivity(in);
            }

        }
    });
}

}

我希望有办法将计时器放入此代码中:P

【问题讨论】:

    标签: android performance android-layout android-intent android-activity


    【解决方案1】:
    import java.util.Timer;
    

    你应该在你的 onResume() 中加入这样的内容:

    Timer timer = new Timer();

        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                Intent intentToResultActivity = new Intent(context, ResultActivity.class);
                context.startActivity(intentToResultActivity);
            }
        }, 10000);`
    

    其中“context”是当前Activity的this,ResultActivity.class是你想要在计时器用完后显示的Activity的名称。

    【讨论】:

    • 计时器会在哪里显示?作为 textview 还是?
    • 这段代码会设置一个只执行一次的隐藏计时器,它的作用是显示活动的结果。如果你想要一个倒数计时器,你可以使用类似的代码和文本视图。不同之处在于你应该在定时器任务中提供第二个参数,例如“}, 0, 1000”,这样代码将立即执行,并且每 1000 毫秒重复一次。在代码主体中,您可以减少文本视图所持有的值。
    • 呃,你能教我怎么做吗?因为 youtube 上没有教程所以我不知道它的想法
    【解决方案2】:

    好的。这是倒数计时器的代码。您应该检查它并根据自己的需要集成它:

    您有两个活动 - Activity1 用于倒计时,而 Activity2 是计时器用完后的结果活动。

    Activity1.java:

    package com.example.emily.countdowntimer;
    
    import android.content.Context;
    import android.content.Intent;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.widget.TextView;
    
    import java.util.Timer;
    import java.util.TimerTask;
    
    public class Activity1 extends AppCompatActivity {
    
        Context context = this;
        Timer timer;
        int countdownValue = 10;
        TextView countdownTextView;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_1);
    
            //this view will hold the countdown value
            countdownTextView = (TextView)findViewById(R.id.countdown);
    
            //we create a new timer and then schedule a task which will execute every one second
            //(it will change the value of the text view)
            timer = new Timer();
    
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            countdownValue--;
                            countdownTextView.setText("" + countdownValue);
    
                            //when the value of the countdown reaches 0, we start the result activity:
                            if (countdownValue == 0) {
                                Intent intentToResultActivity = new Intent(context, Activity2.class);
                                context.startActivity(intentToResultActivity);
                                timer.cancel();
                            }
                        }
                    });
                }
            },0, 1000);
    
        }
    
    }
    

    activity_1.xml:

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
        android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".Activity1">
    
        <TextView android:text="Time Left:" android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="100dp"
            android:textSize="28sp"/>
    
        <TextView android:text="10" android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id = "@+id/countdown"
            android:layout_centerInParent="true"
            android:padding="5dp"
            android:textColor="#ff111d"
            android:textSize="58sp"/>
    
    </RelativeLayout>
    

    Activity2.java:

    package com.example.emily.countdowntimer;
    
    
    import android.os.Bundle;
    import android.support.v7.app.AppCompatActivity;
    
    public class Activity2 extends AppCompatActivity {
    
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_2);
        }
    
    }
    

    activity_2.xml:

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical" android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#406447">
    
        <TextView android:text="Result Activity" android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="100dp"
            android:layout_centerInParent="true"
            android:textColor="#ffffff"
            android:textSize="28sp"/>
    
    </RelativeLayout>
    

    AndroidManifest.xml:

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.example.emily.countdowntimer" >
    
        <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:theme="@style/AppTheme" >
            <activity
                android:name=".Activity1"
                android:label="@string/app_name" >
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
    
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
    
            <activity
                android:name=".Activity2"
                android:label="Result Activity" >
            </activity>
        </application>
    
    </manifest>
    

    这就是您需要的所有代码。我建议你把它放在你的 Android Studio 中,看看它是如何工作的。当您使用它时,更容易理解代码。

    【讨论】:

      【解决方案3】:

      请尝试下面的倒数计时器代码:

          long durationSec = (duration * 60L);
          final long durationInMilliSec = TimeUnit.SECONDS.toMillis(durationSec);
      
          CountDownTimer countDownTimer= new CountDownTimer(durationInMilliSec, 1000) {
              public void onTick(long millisUntilFinished) {
                  tvQuestionAnswerTimer.setText("" + String.format("%02d : %02d : %02d ",
                          TimeUnit.MILLISECONDS.toHours(millisUntilFinished),
                          TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished),
                          TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) -
                                  TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished))));
              }
              public void onFinish() {
                      Toast.makeText(this,Time's up!, Toast.LENGTH_SHORT).show();
              }
          }.start();
      

      在这段代码中

      duration 是 long 类型的分钟数。

      durationSec 是 long 类型的秒数。

      durationInMilliSec 是 long 类型的毫秒数。

      然后毫秒转换为倒计时的小时、分钟和秒。

      我希望它对你有用。

      【讨论】:

        猜你喜欢
        • 2014-11-30
        • 1970-01-01
        • 1970-01-01
        • 2017-05-09
        • 1970-01-01
        • 2016-04-02
        • 1970-01-01
        • 1970-01-01
        • 2016-02-21
        相关资源
        最近更新 更多