url을 입력하고, '인터넷 페이지 열기' 버튼을 누르면 해당 페이지로 가는 기능 구현
package com.example.myapplication
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.widget.Button
import android.widget.EditText
import androidx.appcompat.app.AppCompatActivity
class IntentTest : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_intent_test)
// editText와 button id로 찾기
val button: Button = findViewById(R.id.button)
val editText: EditText = findViewById(R.id.editText)
// 버튼을 누르면
button.setOnClickListener {
// editText에 입력된 text(url 주소)를 받아서
val address = editText.text.toString()
// intent에 해당 주소정보를 넣어 만든다.
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(address))
startActivity(intent)
}
}
}
EditText에 있는 텍스트 가져와서 변수에 담기
val address = editText.text.toString()
- getText()는 Editable객체를 반환하기 때문에 변수에 담기 위해서는 toString() 메소드를 써서 문자열로 만들어줘야 한다.
editText.addTextChangedListener(object : TextWatcher{
// 텍스트가 변하기 전에
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
}
// 텍스트가 변하고있을 때
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
}
// 텍스트가 모두 변화된 후에
override fun afterTextChanged(s: Editable?) {
}
})
object: TextWatcher{
}
를 쓰고 안에 구현해야하는 메소드들을 오버라이드해서 작성하면 된다!