[Kotlin] Activity 전환 & Fragment 전환& Intent로 Data 전달

ddwwon·2022년 11월 3일
0

Android

목록 보기
6/8
post-thumbnail

버튼 클릭 시, 화면 이동 및 TextView 글자 변경

  • Intent를 사용해서 서로 통신하는 Activity
  • EditText에 글자 입력
  • 보내기 버튼 클릭 시, 다음 Activity로 이동 및 다음 Activity의 TextView에 EditText 내용 적용되게

SendMessageActivity.kt

메세지를 보내는 Activity

  • Binding
val sendBinding = ActivitySendMessageBinding.inflate(layoutInflater)
  • Button ClickListener
        sendBinding.sentMessage.setOnClickListener {
            var messageContent = sendBinding.messageInput.text.toString()
            val receivedMessageIntent = Intent(this, ReceivedMessageActivity::class.java)
            receivedMessageIntent.putExtra("message", messageContent)
            startActivity(receivedMessageIntent)
            finish()
        }
  • EditText의 내용 가져오기
var messageContent = sendBinding.messageInput.text.toString()
  • Intent 생성
val receivedMessageIntent = Intent(this, ReceivedMessageActivity::class.java)
            receivedMessageIntent.putExtra("message", messageContent)

intent를 통해서 EditText의 내용을 다음 Activity로 전송!

  • 다음 Activity로 전환
startActivity(receivedMessageIntent)
finish()
  • 전체 코드
package com.example.intentpractice

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.example.intentpractice.databinding.ActivitySendMessageBinding

class SendMessageActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val sendBinding = ActivitySendMessageBinding.inflate(layoutInflater)
        setContentView(sendBinding.root)

        sendBinding.sentMessage.setOnClickListener {
            var messageContent = sendBinding.messageInput.text.toString()
            val receivedMessageIntent = Intent(this, ReceivedMessageActivity::class.java)
            receivedMessageIntent.putExtra("message", messageContent)
            startActivity(receivedMessageIntent)
            finish()
        }
    }
}
  • xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center"
    tools:context=".SendMessageActivity">

    <EditText
        android:id="@+id/messageInput"
        android:layout_width="300dp"
        android:layout_height="50dp"
        android:hint="메세지를 입력하세요."
        android:gravity="center" />

    <Button
        android:id="@+id/sentMessage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="보내기" />

</LinearLayout>

ReceivedMessageActivity.kt

메세지를 받는 Activity

  • Intent로 받아온 EditText의 내용 TextView에 적용하기
receivedBinding.receivedMessage.text = intent.getStringExtra("message")
  • 전체 코드
package com.example.intentpractice

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import com.example.intentpractice.databinding.ActivityReceivedMessageBinding

class ReceivedMessageActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val receivedBinding = ActivityReceivedMessageBinding.inflate(layoutInflater)

        setContentView(receivedBinding.root)
        receivedBinding.receivedMessage.text = intent.getStringExtra("message")

        receivedBinding.changeActicity.setOnClickListener {
            val nextActivityIntent = Intent(this, NextActivity::class.java)
            startActivity(nextActivityIntent)
        }
    }
}
  • xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center"
    tools:context=".ReceivedMessageActivity">

    <TextView
        android:id="@+id/receivedMessage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="전달받은 내용"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"/>

    <Button
        android:id="@+id/change_acticity"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="다음 액티비티로 이동"/>

</LinearLayout>

Fragment에서 Fragment로 전환

NextActivity.kt

ReceivedMessageActivity.kt에서 다음 액티비티로 이동 버튼 클릭 시 이동되는 화면

  • 두 개의 Fragment 생성
val firstFragment = FirstFragment()
val secondFragment = SecondFragment()
  • supportFragmentManager를 사용해서 Fragment 전환
    Activity에 Fragment 씌우기

버튼 클릭 시, Fragment 전환(Fragment 간 전환)

        ch_btn1.setOnClickListener {
            supportFragmentManager.beginTransaction().replace(nextBinding.framelayout.id, firstFragment).commit()
        }
        ch_btn2.setOnClickListener {
            supportFragmentManager.beginTransaction().replace(nextBinding.framelayout.id, secondFragment).commit()
        }
  • 전체 코드
package com.example.intentpractice

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.fragment.app.FragmentManager
import com.example.intentpractice.databinding.ActivityNextBinding
import com.example.intentpractice.databinding.ActivityReceivedMessageBinding

class NextActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val nextBinding = ActivityNextBinding.inflate(layoutInflater)
        setContentView(nextBinding.root)

        val firstFragment = FirstFragment()
        val secondFragment = SecondFragment()

        val ch_btn1 = nextBinding.changeBtn1
        val ch_btn2 = nextBinding.changeBtn2

        supportFragmentManager.beginTransaction().replace(nextBinding.framelayout.id, firstFragment).commit()

        ch_btn1.setOnClickListener {
            supportFragmentManager.beginTransaction().replace(nextBinding.framelayout.id, firstFragment).commit()
        }
        ch_btn2.setOnClickListener {
            supportFragmentManager.beginTransaction().replace(nextBinding.framelayout.id, secondFragment).commit()
        }
    }
}
  • xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".NextActivity">

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/framelayout"
        tools:layout = "@layout/fragment_first"
        android:layout_weight="1"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:gravity="center">

        <Button
            android:id="@+id/change_btn1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Fragment 1으로 전환"
            android:layout_marginRight="5dp"
            android:layout_marginLeft="5dp"/>

        <Button
            android:id="@+id/change_btn2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Fragment 2로 전환"
            android:layout_marginRight="5dp"
            android:layout_marginLeft="5dp"/>

    </LinearLayout>

</LinearLayout>

0개의 댓글