Android 프로그래밍 2

본문 바로가기

사이트 내 전체검색


8. Fragment pass arguments

페이지 정보

작성자 관리자 댓글 0건 조회 3,332회 작성일 20-07-02 21:05

본문


1. 새프로젝트 생성


프로젝트명 : FragmentTest2



2. MainActivity와 레이아웃 수정


파일명 : activity_main.xml


<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
tools:context=".MainActivity"
android:id="@+id/host">

</androidx.constraintlayout.widget.ConstraintLayout>


파일명 : MainActivity.kt


package kr.co.leelab.fragmenttest2

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.fragment.app.Fragment

class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Initially display the first fragment in main activity
// Here we do not pass any arguments
replaceFragment(FirstFragment())
}
}

// Extension function to replace fragment
fun AppCompatActivity.replaceFragment(fragment: Fragment){
val fragmentManager = supportFragmentManager
val transaction = fragmentManager.beginTransaction()
transaction.replace(R.id.host,fragment)
transaction.addToBackStack(null)
transaction.commit()
}


3. 첫번째 래이아웃과 Fragment 클래스 추가


파일명 : fragment_first.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:text="First Fragment"
android:textAppearance="@style/TextAppearance.AppCompat.Large"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:padding="25dp"
/>
<Button
android:id="@+id/btnNavigate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:text="Go To Second Fragment"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView"
/>
</androidx.constraintlayout.widget.ConstraintLayout>


파일명 : FirstFragment.kt

package kr.co.leelab.fragmenttest2

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment

class FirstFragment : Fragment() {

override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val v = inflater.inflate(R.layout.fragment_first, container, false)

// Get the activity and widget
val context = activity as AppCompatActivity
val btnNavigate: Button = v.findViewById(R.id.btnNavigate)
val textView: TextView = v.findViewById(R.id.textView)


// Get the arguments from the caller fragment/activity
val name = arguments?.getString("name")
val age = arguments?.getInt("age")

name?.let {
textView.append("\nName: $name")
}

age?.let {
textView.append("\nAge: $it")
}


// Replace fragment
btnNavigate.setOnClickListener {
// Pass data to fragment
val args = Bundle()
// Send string data as key value format
args.putString("color","#FFFF00")
val fragment = SecondFragment()
fragment.arguments = args

context.replaceFragment(fragment)
}

return v
}
}


4. 두번째 래이아웃과 Fragment 클래스 추가


파일명 : fragment_second.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:text="Second Fragment"
android:textAppearance="@style/TextAppearance.AppCompat.Large"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:padding="25dp"
/>
<Button
android:id="@+id/btnNavigate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:text="Go To First Fragment"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView"
/>
</androidx.constraintlayout.widget.ConstraintLayout>


파일명 : SecondFragment.kt


package kr.co.leelab.fragmenttest2

import android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment

class SecondFragment : Fragment() {

override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val v = inflater.inflate(R.layout.fragment_second, container, false)

// Get the activity and widget
val context = activity as AppCompatActivity
val btnNavigate: Button = v.findViewById(R.id.btnNavigate)
val textView: TextView = v.findViewById(R.id.textView)

// Receive the data from caller fragment/activity
val color = arguments?.getString("color")
color?.let {
textView.setBackgroundColor(Color.parseColor(it))
}

// Replace fragment
btnNavigate.setOnClickListener {
val name = "Junwon Lee"
val age = 25
val bundle = Bundle()
bundle.putString("name",name)
bundle.putInt("age",age)
val fragment = FirstFragment()
fragment.arguments = bundle

// Call the extension function for fragment transaction
context.replaceFragment(fragment)
}

return v
}
}


5. 실행




1.PNG

2.PNG

3.PNG

댓글목록

등록된 댓글이 없습니다.



개인정보취급방침 서비스이용약관
Copyright © www.leelab.co.kr All rights reserved.
상단으로
TEL. 063-469-4551 FAX. 063-469-4560
전북 군산시 대학로 558
군산대학교 컴퓨터정보공학과
PC 버전으로 보기