Coding/Android(kotlin)
버튼(Button) 클릭시 alert dialog띄우기
코딩;
2022. 2. 8. 04:40
1. app - src - main - res - values - strings.xml
<resources>
<string name="app_name">sample10</string>
<string name="edit_hint">이름 입력</string>
</resources>
2. activity_main.xml
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<EditText
android:layout_width="377dp"
android:layout_height="85dp"
android:inputType="text"
android:hint="@string/edit_hint"
android:ems="10"
android:id="@+id/editText"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"/>
<Button
android:text="Button"
android:layout_width="377dp"
android:layout_height="74dp"
android:id="@+id/button"
app:layout_constraintTop_toBottomOf="@+id/editText"
android:layout_marginTop="20dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.502"/>
</androidx.constraintlayout.widget.ConstraintLayout>
1에 설정한 EditText태그 내 android:hint값을 지정하면
android:hint="@string/edit_hint"

3. MainActivity.kt
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val button = findViewById<Button>(R.id.button)
val edit = findViewById<EditText>(R.id.editText)
button.setOnClickListener {
AlertDialog.Builder(this@MainActivity)
.setTitle("대화상자 제목")
.setMessage(edit.text)
.setCancelable(false)
.setNeutralButton("닫기", DialogInterface.OnClickListener{_,_ ->
}).show()
}
}
}
