2017-09-04 117 views
1

如何檢查EditText是否爲空?輸入型數字檢查EditText是否爲空kotlin android

package com.example.www.myapplication 

import android.support.v7.app.AppCompatActivity 
import android.os.Bundle 
import kotlinx.android.synthetic.main.activity_main.* 
import java.util.* 

class MainActivity : AppCompatActivity() { 

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

     val inter:Int=editText.text.toString().toInt() 
     val year: Int = Calendar.getInstance().get(Calendar.YEAR) 
     val res:Int=year-inter 
     textView.text=res.toString() 
    } 
} 
+0

你應該張貼,而不是發佈的ANR截圖堆棧跟蹤。 – BakaWaii

回答

2

下面是說明全例子。

//init the edittext 
    val etMessage = findViewById(R.id.et_message) as EditText 
    //init the button 
    val btnClick = findViewById(R.id.btn_click) as Button 

    btnClick.setOnClickListener{ 
     //read value from EditText to a String variable 
     val msg: String = etMessage.text.toString() 

     //check if the EditText have values or not 
     if(msg.trim().length>0) { 
      Toast.makeText(applicationContext, "Message : "+msg, Toast.LENGTH_SHORT).show() 
     }else{ 
      Toast.makeText(applicationContext, "Please enter some message! ", Toast.LENGTH_SHORT).show() 
     } 
    } 
0

試試這個:

if(TextUtils.isEmpty(editText.getText().toString())){  
    //Do 
} 
+0

謝謝顯示輸入調試圖像說明 –

1

嘿,我使用這樣的科特林

val input = editText?.text.toString().trim() 
    if (input.isNullOrBlank()) { 
     //Your code for blank edittext 
    } 

希望這將有助於you..let我知道如果有任何問題....

+0

大多數情況下,如果您想從輸入框中獲取文本,請使用像 「val input = editText?.text.toString()。trim()」 –

+0

未解決的參考。由於接收器類型不匹配,以下候選者都不適用: @InlineOnly public inline fun CharSequence?.isNullOrBlank():在kotlin.text中定義的布爾值 –

0
var userName = editText!!.text.toString().trim() 
if (userName.equals("")) { 
    //TODO Something Here 
} 
+1

雖然答案總是值得讚賞,但它確實有助於提供有關**的其他信息**代碼如何解決手頭的問題。這樣做可以幫助那些具有類似(但不完全相同)問題的人。不是每個人都可能熟悉你的確切編碼邏輯,但可以理解你的一般*方法*或*概念*。爲了幫助改進您的答案,請提供一些[**環境**](https://meta.stackexchange.com/questions/114762),並參閱關於[**寫出優秀答案**]的幫助文章( http://stackoverflow.com/help/how-to-answer)關於如何使您的答案計數的一些提示:) –

1

線束科特林功率通過使用內聯擴展函數:

editText.text.isNotEmpty().apply { 
    //do something 
} 

,或者使用let

+0

謝謝show show enter image description –

0

了一個新的傢伙,他想地段,這爲我工作

 if(!editTextTerminalName.text.toString().trim().isNotEmpty()) { 

       editTextTerminalName?.error = "Required" 

      }else if(!editTextPassword.text.toString().trim().isNotEmpty()){ 


       editTextPassword?.error = "Required" 
      }else{ 

       avi.visibility= View.VISIBLE // v letter should be capita 
} 
0

嘗試了這一點:

//button from xml 
botton.setOnClickListener{           
val new=addText.text.toString()//addText is an EditText 
if(new=isNotEmpty()) 
{ 
    //do something 
} 
else{ 
Toast.makeText(applicationContext, "Enter some message ", Toast.LENGTH_SHORT).show() 
} 
}