【问题标题】:Convert EditText text to uppercase and lowercase , when clicked on button?单击按钮时将 EditText 文本转换为大写和小写?
【发布时间】:2020-01-30 12:27:28
【问题描述】:

我想要做的是从用户那里获取输入,然后在按钮单击事件中我想在 TextView 上显示 EditText 输入。在按钮单击侦听器上,textView 应该以全部大写形式显示输入字符串,然后单击同一个按钮,它应该将该字符串转换为小写并在TextView 上显示。我怎样才能做到这一点?

这是我尝试过的。

var userInput = findViewById<EditText>(R.id.editText)
var caseButton = findViewById<Button>(R.id.upperLowerButton)
var caseView = findViewById<TextView>(R.id.textUpperLower)

caseButton.setOnClickListener {
    caseView.text =  userInput.text
}

【问题讨论】:

标签: android kotlin android-edittext


【解决方案1】:

你可以使用类似的东西:

val uppercase = userInput.text.toString().toUpperCase()
val lowerCase = uppercase.toLowerCase()

【讨论】:

    【解决方案2】:

    使用方法 - toUpperCase() 和 toLowerCase() 可以轻松解决这个问题。

    button.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        String h =  textView.getText().toString();
                        if (isCaps) {
                            textView.setText(h.toUpperCase());
                            isCaps = false;
                        }
                           else {
                               textView.setText(h.toLowerCase());
                           isCaps = true;}
                        }
        
                });
    

    【讨论】:

      【解决方案3】:

      您可以使用.toUpperCase().toLowerCase() 作为字符串值,例如

      userInput.text.toString().toUpperCase() 
      

      userInput.text.toString().toLowerCase()
      

      【讨论】:

        【解决方案4】:

        你可以尝试如下。

        var isUpperCase = false;
        var txt = userInput.text.toString()
        caseButton.setOnClickListener {
              if(isUpperCase){
                 txt = txt.toLowerCase()
                 isUpperCase = false
              }else{
                  txt = txt.toUpperCase()
                  isUpperCase = true
              }
               caseView.text =  txt
        }
        

        【讨论】:

          【解决方案5】:

          在 Kotlin 中,toUperCase()toLowerCase() 已被弃用,我们可以使用 uppercase() 代替 toUpperCase()lowercase() 代替 toLowerCase()

          例如,

          val lower="abc"
          Log.e("TAG", "Uppercase: ${lower.uppercase()}" ) //ABC
          val upper="ABC"
          Log.e("TAG", "Lowercase: ${upper.lowercase()}" ) //abc
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2021-01-28
            • 2011-07-21
            • 2018-08-17
            • 1970-01-01
            • 2022-01-24
            • 2011-11-05
            相关资源
            最近更新 更多