如何在Android应用中多次单击按钮并更改模式

时间:2019-09-18 17:15:03

标签: android kotlin onclicklistener

我是Android开发的新手。我需要构建一个温度转换器应用程序,以将Celcius转换为Farenheit,将Farenheit转换为Celcius。我已将editText用于用户输入。有两个按钮。一个按钮是转换输入,另一个按钮是模式按钮,它将在两种转换模式之间切换。当我启动应用程序时,默认情况下该模式处于摄氏状态。通过单击模式按钮,我可以将模式更改为摄氏度。问题是,当我再次单击模式按钮时,它不会返回到摄氏到华氏转换模式。我不知道该怎么做。有人可以在这方面帮助我吗?

我为转换按钮设置了功能getset(),为模式按钮设置了功能mode()。

fun getSet(view: View)
{
    val convert = findViewById<Button>(R.id.button)
    convert.setOnClickListener {
        if(editText.length()==0)
        {
            editText.setError("Enter a Value")
        }
        else
        {
            val editxt = findViewById<EditText>(R.id.editText)
            val msg = editxt.text.toString()
            val txtview = findViewById<TextView>(R.id.textView2).apply {
                val cel = msg.toDouble()
                val far =  (cel*1.8)+32
                    text = "Result: " + far.toString()
                }
            }
        }
  }
  fun mode(view: View)
  {
    val convert = findViewById<Button>(R.id.button)
    val heading = findViewById<TextView>(R.id.textView).apply {
            val caption =  "Farenheit to Celcius"
            text = caption
        }
    convert.setOnClickListener {
        if(editText.length()==0)
        {
                editText.setError("Enter a Value")
        }
        else
        {
            val editxt = findViewById<EditText>(R.id.editText)
            val msg = editxt.text.toString()
            val txtview = findViewById<TextView>(R.id.textView2).apply {
                    val far = msg.toDouble()
                    val cel =  (far-32)*0.5555555556
                    text = "Result: " + cel.toString()
            }
        }
    }
}

1 个答案:

答案 0 :(得分:2)

您需要将“模式”存储在全局变量中。 创建一个全局变量

var isModeCelsius: Boolean = true

现在在活动的onCreate()方法内,在setContentView(R.layout.your_layout_name)行下输入以下代码。

//Initialize edittext and button
    val convert = findViewById<Button>(R.id.button)
    val heading = findViewById<TextView>(R.id.textView)
    val modeButton = findViewById<Button>(R.id.id_of_button)
    val editxt = findViewById<EditText>(R.id.editText)
    val showResultTextView = findViewById<TextView>(R.id.textView2)
    //You only need to assign the click listener once
    modeButton.setOnClickListener {
        if (isModeCelsius) {
            isModeCelsius = false
        } else {
            isModeCelsius = true
        }

        //Or you can simply use
        //isModeCelsius=!isModeCelsius
    }
    convert.setOnClickListener {
        val msg = editxt.text.toString()
        if(isModeCelsius){
            val far = msg.toDouble()
            val cel =  (far-32)*0.5555555556
            showResultTextView.text = "Result: " + cel.toString()
        }else{
            val cel = msg.toDouble()
            val far =  (cel*1.8)+32
            showResultTextView.text = "Result: " + far.toString()
        }
    }