본문 바로가기

프로젝트형 IoT 서비스 개발 4회차/3. 게이트웨이 디바이스 제어

[Day72] 2022-05-09(월) Android11 - Fragment2 - 김서연 강사님

728x90

[1] Fragment

  1. 데이터 전달 예제

    - Activity -> Fragment 로 데이터 전달 (Activity/Fragment가 주체가 될 수 있음)

    - Fragment -> Activity 로 데이터 전달 (Activity/Fragment가 주체가 될 수 있음)

    1) 메인 Activity

activity_fragment_exam.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:id="@+id/maindataView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="메인액티비티데이터:"
            />
        <EditText
            android:id="@+id/maindata"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"/>
        <Button
            android:id="@+id/btn_get"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="데이터가져오기"
            />
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:id="@+id/senddataView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="메인액티비티데이터:"
            />
        <EditText
            android:id="@+id/senddata"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"/>
        <Button
            android:id="@+id/btn_set"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="프레그먼트로 데이터 보내기"
            />
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:id="@+id/fragmentView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="프레그먼트에서 전달된 데이터:"
            />
        <EditText
            android:id="@+id/fragment_data"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"/>

    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"

        android:background="#FFC107"
        android:orientation="horizontal">

        <Button
            android:id="@+id/btn_showregister"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:tag="first"
            android:onClick="btn_click"
            android:text="회원가입" />

        <Button
            android:id="@+id/btn_showlogin"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:tag="second"
            android:onClick="btn_click"
            android:text="로그인" />

        <Button
            android:id="@+id/btn_showmypage"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:tag="third"
            android:onClick="btn_click"
            android:text="마이페이지" />
    </LinearLayout>
    <FrameLayout
        android:id="@+id/exam_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    </FrameLayout>
</LinearLayout>

SetGetTestFragmentActivity.kt

package com.example.fragment.fragment

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.fragment.app.FragmentManager
import com.example.fragment.R
import kotlinx.android.synthetic.main.activity_exam_fragment_main.*
import kotlinx.android.synthetic.main.activity_fragment_exam.*

class SetGetTestFragmentActivity : AppCompatActivity() {
    val view1:RegisterFragment = RegisterFragment()
    val view2:LoginFragment = LoginFragment()
    val view3:MyPageFragment = MyPageFragment()
    var fragmentManager:FragmentManager? = null
    var obj:RegisterFragment? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_fragment_exam)

        fragmentManager = supportFragmentManager

        // 프레그먼트 -> 액티비티 데이터 전달
        btn_get.setOnClickListener {
            // findFragmentById -> 현재 연결된 fragment를 리턴 (화면에 보이는 프레그먼트를 리턴)
            // 어떤 프레그먼트가 연결되어 있는지 알 수 없으므로 상위타입인 Fragment를 반환
            // 따라서 우리가 사용할 프레그먼트(RegisterFragment)로 캐스팅
            obj = fragmentManager?.findFragmentById(R.id.exam_container) as RegisterFragment
            maindata.setText(obj?.sendData())
        }

        // 액티비티 -> 프레그먼트 데이터 전달
        btn_set.setOnClickListener {
            obj = fragmentManager?.findFragmentById(R.id.exam_container) as RegisterFragment
            obj?.receiveData(senddata.text.toString())
        }
    }

    fun btn_click(view: View){
        changeFragment(view.tag.toString())
    }

    fun changeFragment(name:String){
        val transaction = fragmentManager?.beginTransaction()
        when(name){
            "first" -> {
                transaction?.replace(R.id.exam_container, view1)
                transaction?.addToBackStack("first")
            }
            "second" -> {
                transaction?.replace(R.id.exam_container, view2)
                transaction?.addToBackStack("second")
            }
            "third" -> {
                transaction?.replace(R.id.exam_container, view3)
                transaction?.addToBackStack("third")
            }
        }
        transaction?.commit()

    }
}

    2) 첫 번째 Fragment

register.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#4CAF50"
    android:orientation="vertical">

    <TextView
        android:id="@+id/textView3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="회원가입"
        android:textSize="36sp" />

    <EditText
        android:id="@+id/edit_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="textPersonName"

        android:hint="이름"/>

    <EditText
        android:id="@+id/edit_id"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="textPersonName"
        android:hint="id" />

    <EditText
        android:id="@+id/edit_pass"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="textPersonName"
        android:hint="password" />

    <Button
        android:id="@+id/btn_insert"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="가입" />
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="액티비티에서 보내온 값:"/>
        <EditText
            android:id="@+id/setdata_fragment"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
    </LinearLayout>
</LinearLayout>

RegisterFragment.kt

package com.example.fragment.fragment

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.example.fragment.R
import kotlinx.android.synthetic.main.activity_fragment_exam.*
import kotlinx.android.synthetic.main.register.*

class RegisterFragment : Fragment() {

    var data:String?=null
    override fun onCreateView(inflater: LayoutInflater,container: ViewGroup?,savedInstanceState: Bundle?): View? {
        val view =  inflater.inflate(R.layout.register, container, false)
        return view
    }
    //View가 메모리에 할당된 후 호출되는 메소드에서 처리한다.
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        // 프레그먼트의 각 뷰에 이벤트를 연결하기 위한 메소드
        btn_insert.setOnClickListener {
            val data = sendData()
            // 프레그먼트가 붙어있는 액티비티(부모 액티비티)를 받아오기
            // 프레그먼트에서 getActivity( ) 하면 부모 액티비티를 구할 수 있다.
            val parentview = activity as SetGetTestFragmentActivity
            parentview.fragment_data.setText(data)

            setdata_fragment.text = parentview.senddata.text
        }
    }
    // 액티비티에 값을 보내고 액티비티에서 보내오는 값을 세팅할 메소도를 준비
    // 코틀린은 멤버변수를 이용해서 set/get 메소드를 자동으로 구현하기 때문에 사용자정의 메소드명은 피해서 정의
    // 1. 액티비티로 데이터를 보내기 위한 메소드
    fun sendData():String {
        val data = "아이디:${edit_id.text}, 성명:${edit_name.text}, 패스워드:${edit_pass.text}"
        return data
    }
    // 2. 액티비티에서 보내오는 데이터를 받기 위한 메소드
    fun receiveData(data:String){
        setdata_fragment.setText(data)
    }

}

    3) 두 번째 Fragment

login.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#009688"
    android:orientation="vertical">

    <TextView
        android:id="@+id/textView4"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="로그인"
        android:textSize="36sp" />

    <EditText
        android:id="@+id/editText4"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="textPersonName"
        android:hint="id" />

    <EditText
        android:id="@+id/editText5"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="textPassword"
        android:hint="pass"/>

    <Button
        android:id="@+id/button5"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="로그인" />
</LinearLayout>

LoginFragment.kt

package com.example.fragment.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.example.fragment.R

class LoginFragment : Fragment() {
    override fun onCreateView(inflater: LayoutInflater,container: ViewGroup?,savedInstanceState: Bundle?): View? {

        // Inflate the layout for this fragment
        val view =  inflater.inflate(R.layout.login, container, false)
        return view
    }

}

    4) 세 번째 Fragment

mypage.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#8BC34A"
    android:orientation="vertical">
     <TextView
            android:id="@+id/textView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="회원정보"
            android:textSize="30sp" />

        <ImageView
            android:id="@+id/imageView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:src="@drawable/img01" />

        <TextView
            android:id="@+id/textView2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="장기용" />


</LinearLayout>

MyPageFragment.kt

package com.example.fragment.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.example.fragment.R

class MyPageFragment : Fragment() {
    override fun onCreateView(inflater: LayoutInflater,container: ViewGroup?,savedInstanceState: Bundle?): View? {

        // Inflate the layout for this fragment
        val view =  inflater.inflate(R.layout.mypage, container, false)
        return view
    }

}

Activity 가 주체
Fragment 가 주체

 

- 끝 -

728x90