Android Kotlin计算速度(时间)

时间:2017-10-03 08:30:34

标签: android time kotlin

所以......我已经在这2天了,这让我发疯了。

我正在努力使layout工作。它应该是时间和/或步速计算器。我是先尝试一次,但是2天后这种情况还不顺利。

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_running_calculator)

    var distanceView = findViewById<NumberPicker>(R.id.distanceTxtField) as TextView
    var timeView = findViewById<NumberPicker>(R.id.timeTxtField) as TextView
    var paceView = findViewById<NumberPicker>(R.id.paceTxtField) as TextView
    var calculateBtn = findViewById<Button>(R.id.calculateBtn)
    var resultView = findViewById<TextView>(R.id.textView5)

// ............

  fun calculationPaceKm () {

        var stringArray = timeView.text.toString().split(":")
        var total = stringArray[0].toDouble()
        total += (stringArray[1].toDouble() / 60 )
        var distanceValue = distanceView.text.toString().toDouble()
        var resultPaceKm = ((distanceValue / total) * 1.37).toDouble()
        var resultFormatPaceMiles = "%.1f pace".format(resultPaceKm)
        resultView.setText(resultFormatPaceMiles.toString())}

kmBtn.setOnClickListener{

            calculationPaceKm()


            }

我不知道怎么回事......我的结果非常奇怪,没有任何效果:/

由于

=======================

修改

所以我编辑了我的问题,所以你可以看到我拥有的东西。这几乎是你给我的东西,但有一些调整。我注意到的是它没有正确地改变我的距离而且我不知道为什么。让我们说我将7.37Km兑换成Miles。它应该给我4.58英里,但我得到4.35英里,好像我乘以0.59,我不是。我乘以0.621371

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    val time = findViewById<NumberPicker>(R.id.time) as TextView
    val distance = findViewById<NumberPicker>(R.id.distance) as TextView
    val pace = findViewById<NumberPicker>(R.id.pace) as TextView




    calculate.setOnClickListener {

        when {

            time.text.isEmpty() && (distance.text.isNotEmpty() && pace.text.isNotEmpty()) ->
                calculatePace(null, distance.text.toString(), pace.text.toString())

            distance.text.isEmpty() && (time.text.isNotEmpty() && pace.text.isNotEmpty()) ->
                calculatePace(time.text.toString(), null, pace.text.toString())

            pace.text.isEmpty() && (time.text.isNotEmpty() && distance.text.isNotEmpty()) ->
                calculatePace(time.text.toString(), distance.text.toString(), null)

            else -> {
                Toast.makeText(this, "Please check all fields",
                        Toast.LENGTH_SHORT).show()
            }
        }
    }

}


fun Double.format(digits: Int) = java.lang.String.format("%.${digits}f", this)


@SuppressLint("SetTextI18n")
private fun calculatePace(time: String?, distance: String?, pace: String?) {


    // KM Distance and KM Pace Button
    if (kmDistanceRadioBtn.isChecked && kmPaceRadioBtn.isChecked)
        when {
        // TIME: To calculate your time, fill in your distance and pace
            time == null -> {
                val calculatedTime = distance!!.toLong() * timeToSeconds(pace.toString())
                result.text = "The runner's time is ${secondsToTime(calculatedTime)}"
            }
        // DISTANCE: To calculate your distance, fill in your time and pace
            distance == null -> {
                val calculatedDistance = (timeToSeconds(time).toDouble().div(timeToSeconds
                (pace.toString()).toDouble())).format(2)
                result.text = "Distance is $calculatedDistance KM"
            }
        // PACE: To calculate your pace, fill in your time and distance
            pace == null -> {
                // Calculate Pace
                val calculatedPace: Long = timeToSeconds(time).toLong() / distance.toLong()

                Log.i("PaceSeconds", calculatedPace.toString() +
                        secondsToTime(calculatedPace))


                result.text = "The runner's pace in KM is ${secondsToTime(calculatedPace)}"
            }
        }

    // Miles Distance and Miles Pace Button
    else if (milesDistanceRadioBtn.isChecked && milesPaceRadioBtn.isChecked)
        when {
        // TIME: To calculate your time, fill in your distance and pace
            time == null -> {
                val calculatedTime = distance!!.toLong() * timeToSeconds(pace.toString())
                result.text = "The runner's time is ${secondsToTime(calculatedTime)}"
            }
        // DISTANCE: To calculate your distance, fill in your time and pace
            distance == null -> {
                val calculatedDistance = (timeToSeconds(time).toDouble().div(timeToSeconds
                (pace.toString()).toDouble())).format(2)
                result.text = "Distance is $calculatedDistance Miles"
            }
        // PACE: To calculate your pace, fill in your time and distance
            pace == null -> {
                // Calculate Pace
                val calculatedPace: Long = timeToSeconds(time).toLong() / distance.toLong()

                Log.i("PaceSeconds", calculatedPace.toString() +
                        secondsToTime(calculatedPace))


                result.text = "The runner's pace in miles is ${secondsToTime(calculatedPace)}"
            }

            // KM Distance and Miles Pace Button
        } else if(kmDistanceRadioBtn.isChecked && milesPaceRadioBtn.isChecked) {
        when {
        // TIME: To calculate your time, fill in your distance and pace
            time == null -> {
                val calculatedTime = distance!!.toLong() * timeToSeconds(pace.toString())
                result.text = "The runner's time is ${secondsToTime(calculatedTime)}"
            }
        // DISTANCE: To calculate your distance, fill in your time and pace
            distance == null -> {
                val calculatedDistance = (timeToSeconds(time).div(timeToSeconds
                (pace.toString())) * 0.621371).format(2)
                result.text = "Distance is $calculatedDistance Miles"
            }
        // PACE: To calculate your pace, fill in your time and distance
            pace == null -> {
                // Calculate Pace
                val calculatedPace: Long = timeToSeconds(time).toLong() / distance.toLong()

                Log.i("PaceSeconds", calculatedPace.toString() +
                        secondsToTime(calculatedPace))


                result.text = "The runner's pace in miles is ${secondsToTime(calculatedPace)}"
            }
        }

        // Miles Distance and KM Pace Button
    } else if(milesDistanceRadioBtn.isChecked && kmPaceRadioBtn.isChecked) {
        when {
        // TIME: To calculate your time, fill in your distance and pace
            time == null -> {
                val calculatedTime = distance!!.toLong() * timeToSeconds(pace.toString())
                result.text = "The runner's time is ${secondsToTime(calculatedTime)}"
            }
        // DISTANCE: To calculate your distance, fill in your time and pace
            distance == null -> {
                val calculatedDistance = (timeToSeconds(time).div(timeToSeconds
                (pace.toString())) * 0.621371).format(2)
                result.text = "Distance is $calculatedDistance Miles"
            }
        // PACE: To calculate your pace, fill in your time and distance
            pace == null -> {
                // Calculate Pace
                val calculatedPace: Long = timeToSeconds(time).toLong() / distance.toLong()

                Log.i("PaceSeconds", calculatedPace.toString() +
                        secondsToTime(calculatedPace))


                result.text = "The runner's pace in miles is ${secondsToTime(calculatedPace)}"
            }
        }


    } else{
        Toast.makeText(this, "Please choose one unit", Toast.LENGTH_SHORT).show()
    }


}

// Convert Time to Seconds
@SuppressLint("SimpleDateFormat")
private fun timeToSeconds(time: String): Long {
    val dateFormat = SimpleDateFormat("mm:ss")
    val reference = dateFormat.parse("00:00")
    val date = dateFormat.parse(time)

    return (date.time - reference.time) / 1000L
}

// Convert Seconds to Time
private fun secondsToTime(seconds: Long): String {
    val hours = seconds / 3600
    val minutes = (seconds % 3600) / 60
    val seconds = seconds % 60

    return String.format("%02d:%02d",minutes, seconds)
}}

1 个答案:

答案 0 :(得分:0)

保持字段为空,您想要计算。

<强> MainActivity.kt

        package com.example.wave18.pacecalculator

import android.annotation.SuppressLint
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.util.Log
import android.view.View
import android.widget.TextView
import kotlinx.android.synthetic.main.activity_main.*
import java.text.SimpleDateFormat


class MainActivity : AppCompatActivity() {
    // Regex for Checking Input time Format
    val regex = Regex("^([0-1]\\d|2[0-3]):([0-5]\\d):([0-5]\\d)\$")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val time = findViewById<View>(R.id.time) as TextView
        val distance = findViewById<View>(R.id.distance) as TextView
        val pace = findViewById<View>(R.id.pace) as TextView


        calculate.setOnClickListener {

            when {


                time.text.isEmpty() && (distance.text.isNotEmpty() && pace.text.isNotEmpty()) -> {

                    if (regex.matches(pace.text)) {
                        calculatePace(null, distance.text.toString(), pace.text.toString())
                    } else {
                        // SHOW ERROR
                    }


                }

                distance.text.isEmpty() && (time.text.isNotEmpty() && pace.text.isNotEmpty()) -> calculatePace(time.text.toString(), null, pace.text.toString())

                pace.text.isEmpty() && (time.text.isNotEmpty() && distance.text.isNotEmpty()) -> calculatePace(time.text.toString(), distance.text.toString(), null)

                else -> {
                    Log.i("Error", "Something wrong You need to enter / empty values")
                }

            }
        }

    }


    @SuppressLint("SetTextI18n")
    private fun calculatePace(time: String?, distance: String?, pace: String?) {


        when {
        // TIME: To calculate your time, fill in your distance and pace
            time == null -> {
                val calulatedTime = distance!!.toLong() * timeToSeconds(pace.toString())
                result.text = "The runner's time is ${secondsToTime(calulatedTime)}"
            }
        // DISTANCE: To calculate your distance, fill in your time and pace
            distance == null -> {
                val calculatedDistance = timeToSeconds(time).toDouble().div(timeToSeconds(pace.toString()))
                result.text = "Distance is $calculatedDistance KM"
            }
        // PACE: To calculate your pace, fill in your time and distance
            pace == null -> {
                // Calculate Pace
                val calculatedPace: Long = timeToSeconds(time).toLong() / distance.toLong()

                Log.i("PaceSeconds", calculatedPace.toString() + secondsToTime(calculatedPace))


                result.text = "The runner's pace is ${secondsToTime(calculatedPace)}"
            }
        }
    }

    // Convert Time to Seconds
    @SuppressLint("SimpleDateFormat")
    private fun timeToSeconds(time: String): Long {
        val dateFormat = SimpleDateFormat("HH:mm:ss")
        val reference = dateFormat.parse("00:00:00")
        val date = dateFormat.parse(time)
        val seconds = (date.time - reference.time) / 1000L

        return seconds
    }


    // Convert Seconds to Time
    private fun secondsToTime(seconds: Long): String {
        val hours = seconds / 3600
        val minutes = (seconds % 3600) / 60
        val seconds = seconds % 60

        val timeString = String.format("%02d:%02d:%02d", hours, minutes, seconds)
        return timeString
    }
}

<强> activity_main.xml中

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.wave18.pacecalculator.MainActivity">

    <EditText
        android:id="@+id/time"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="107dp"
        android:layout_marginStart="62dp"
        android:layout_marginTop="87dp"
        android:ems="10"
        android:inputType="textPersonName"
        android:text="01:10:10"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/distance"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="106dp"
        android:layout_marginStart="63dp"
        android:layout_marginTop="28dp"
        android:ems="10"
        android:inputType="textPersonName"
        android:text="10"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/time" />

    <EditText
        android:id="@+id/pace"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="107dp"
        android:layout_marginStart="62dp"
        android:layout_marginTop="25dp"
        android:ems="10"
        android:inputType="textPersonName"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/distance" />

    <TextView
        android:id="@+id/result"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="24dp"
        android:layout_marginStart="24dp"
        android:layout_marginTop="53dp"
        android:text="TextView"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/pace" />

    <Button
        android:id="@+id/calculate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="165dp"
        android:layout_marginStart="131dp"
        android:layout_marginTop="61dp"
        android:text="Button"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/result" />
</android.support.constraint.ConstraintLayout>