Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,19 @@
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

<activity
android:name=".ActivityA"
android:exported="false"
android:launchMode="standard"
/>

<activity
android:name=".ActivityB"
android:exported="false"
android:launchMode="standard"
/>

</application>

</manifest>
20 changes: 20 additions & 0 deletions app/src/main/java/otus/gpb/homework/fragments/ActivityA.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package otus.gpb.homework.fragments

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

class ActivityA : AppCompatActivity() {

//private lateinit var fragmentA: FragmentA

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_a)
// По клику на кнопку запустите фрагмент транзакцию которая открывает FragmentA.
// в нашем случае "По клику на кнопку" === "при запуске Actity A"
supportFragmentManager.beginTransaction()
.replace(R.id.container_FragmentA, FragmentA())
.addToBackStack(null)
.commit()
}
}
35 changes: 35 additions & 0 deletions app/src/main/java/otus/gpb/homework/fragments/ActivityB.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package otus.gpb.homework.fragments

import android.content.res.Configuration
import android.os.Bundle
import android.view.View
import android.widget.FrameLayout
import androidx.appcompat.app.AppCompatActivity
import java.util.Objects

class ActivityB : AppCompatActivity() {

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

// ландшафтный режим - отобразить оба фрагмента одновременно
if (Objects.equals(Configuration.ORIENTATION_LANDSCAPE, resources.configuration.orientation)) {
findViewById<FrameLayout>(R.id.frameLayout_bb).visibility = View.VISIBLE
supportFragmentManager.beginTransaction()
.replace(R.id.frameLayout_ba, FragmentBA())
.replace(R.id.frameLayout_bb, FragmentBB())
.commit()
}
else {
// портретный режим режим - отобразить только один фрагмент
findViewById<FrameLayout>(R.id.frameLayout_bb).visibility = View.GONE
supportFragmentManager.beginTransaction()
.replace(R.id.frameLayout_ba, FragmentBA())
.commit()
}
}

private fun isLandscape() =
Objects.equals(Configuration.ORIENTATION_LANDSCAPE, resources.configuration.orientation)
}
59 changes: 59 additions & 0 deletions app/src/main/java/otus/gpb/homework/fragments/FragmentA.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package otus.gpb.homework.fragments

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import androidx.activity.OnBackPressedCallback
import androidx.fragment.app.Fragment


class FragmentA : Fragment() {

override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?,
): View? {
val view = inflater.inflate(R.layout.fragment_a, container, false)
val btnOpenFragmentAA = view.findViewById<Button>(R.id.btn_open_FragmentAA)

// Реализуйте обработку нажатия на кнопку “Назад”, используя OnBackPressedDispatcher,
requireActivity().onBackPressedDispatcher.addCallback(
viewLifecycleOwner,
object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
// таким образом, что
if (childFragmentManager.backStackEntryCount == 1) {
// После того как размер стека = 1, закрывайте активити.
requireActivity().finish()
} else {
//по нажатию из стека фрагментов удаляется один фрагмент
childFragmentManager.popBackStack()
}
}
}
)

//В FragmentA добавьте кнопку, которая открывает фрагмент FragmentAA,
// при этом он должен быть child фрагментом для FragmentA.
btnOpenFragmentAA.setOnClickListener {
// проверяем стек транзакций
if (childFragmentManager.backStackEntryCount == 0) {
// стек пустой - создадим FragmentAA
val fragmentAa = FragmentAA()
val args = Bundle()
// При открытии FragmentAA, передайте в него цвет, полученный из рандомайзера ColorGenerator
args.putInt("color", ColorGenerator.generateColor())
fragmentAa.arguments = args
childFragmentManager.beginTransaction()
.add(R.id.layout_FragmentA, fragmentAa)
.addToBackStack(null)
.commit()
}
}

return view
}
}
35 changes: 35 additions & 0 deletions app/src/main/java/otus/gpb/homework/fragments/FragmentAA.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package otus.gpb.homework.fragments

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

class FragmentAA : Fragment() {

override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?,
): View? {
val view = inflater.inflate(R.layout.fragment_aa, container, false)
// ...покрасьте FragmentAA в этот цвет.
arguments?.getInt("color")?.let { view.setBackgroundColor(it) }

view.findViewById<Button>(R.id.btn_open_FragmentAB).setOnClickListener {
val fragmentAb = FragmentAB()
val args = Bundle()
args.putInt("color", ColorGenerator.generateColor())
fragmentAb.arguments = args

parentFragmentManager.beginTransaction()
.replace(R.id.layout_FragmentA, fragmentAb, "fragmentAb")
.addToBackStack(null)
.commit()
}

return view
}
}
23 changes: 23 additions & 0 deletions app/src/main/java/otus/gpb/homework/fragments/FragmentAB.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package otus.gpb.homework.fragments

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

class FragmentAB : Fragment() {

override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?,
): View? {
val view = inflater.inflate(R.layout.fragment_ab, container, false)
// и покрасьте FragmentAA в этот цвет
arguments?.getInt("color")?.let { view.setBackgroundColor(it) }

return view
}
}
55 changes: 55 additions & 0 deletions app/src/main/java/otus/gpb/homework/fragments/FragmentBA.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package otus.gpb.homework.fragments

import android.content.res.Configuration
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import androidx.fragment.app.Fragment
import java.util.Objects

private const val KEY_COLOR = "key_color"

class FragmentBA: Fragment() {

private var color: Int = 0

override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?, ): View? {
val view = inflater.inflate(R.layout.fragment_ba, container, false)

// Покрасте фон FragmentBA в полученный цвет.
parentFragmentManager.setFragmentResultListener(KEY_COLOR, this) { _, bundle ->
color = bundle.getInt(KEY_COLOR)
view.setBackgroundColor(color)
}

val btnOpenFragmentBB = view.findViewById<Button>(R.id.btn_open_FragmentBB)

// Если девайс находится в portrait ориентации, добавьте в FragmentBA кнопку,
// в данном случае кнопку скрываем / показываем
btnOpenFragmentBB.visibility = when (isPortrait()) {
true -> View.VISIBLE
false -> View.GONE
}
// по нажатию на которой будет открываться FragmentBB, на том же уровне иерархии, что и FragmentBA.
btnOpenFragmentBB.setOnClickListener {
parentFragmentManager.beginTransaction()
.replace(R.id.frameLayout_ba, FragmentBB(), "FragmentBB")
.commit()
}
return view
}
// ориентация экрана
private fun isPortrait(): Boolean =
Objects.equals(Configuration.ORIENTATION_PORTRAIT, resources.configuration.orientation)

override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putInt(KEY_COLOR, color)
}

}
55 changes: 55 additions & 0 deletions app/src/main/java/otus/gpb/homework/fragments/FragmentBB.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package otus.gpb.homework.fragments

import android.content.res.Configuration
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import androidx.core.os.bundleOf
import androidx.fragment.app.Fragment
import java.util.Objects

private const val KEY_COLOR = "key_color"

class FragmentBB: Fragment() {

override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?,
): View? {
val view = inflater.inflate(R.layout.fragment_bb, container, false)

// перерисуем fragmentBA с новым цветом
view.findViewById<Button>(R.id.btn_SendColor)
.setOnClickListener {
val args = Bundle()
args.putInt(KEY_COLOR, ColorGenerator.generateColor())
if (isPortrait()) {
// Если девайс находится в portrait ориентации,
// В FragmentBB добавьте кнопку, которая получит цвет из рандомайзера ColorGenerator
// и вернет результат в FragmentBA. Как и в пункте 1, покрасте фон FragmentBA в полученный цвет.
val fragmentBA = FragmentBA()
fragmentBA.arguments = args
parentFragmentManager.beginTransaction()
.replace(R.id.frameLayout_ba, fragmentBA).apply {
fragmentBA.arguments = args
parentFragmentManager.setFragmentResult(KEY_COLOR, args)
}
.commit()
}
else {
// Если девайс находится в landscape ориентации, то расположите фрагменты на одном уровне иерархии.
// В фрагмент FragmentBB добавьте кнопку, по нажатию на которую программа получит цвет из рандомайзера ColorGenerator
// и передаст его в FragmentBA, используя FragmentResultListener.
parentFragmentManager.setFragmentResult(KEY_COLOR, args)
}
}

return view
}
// ориентация экрана
private fun isPortrait(): Boolean =
Objects.equals(Configuration.ORIENTATION_PORTRAIT, resources.configuration.orientation)
}
12 changes: 12 additions & 0 deletions app/src/main/java/otus/gpb/homework/fragments/MainActivity.kt
Original file line number Diff line number Diff line change
@@ -1,12 +1,24 @@
package otus.gpb.homework.fragments

import android.content.Intent
import android.os.Bundle
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

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

// Реализуйте кнопки перехода в активити с фрагментами в MainActivity.
findViewById<Button>(R.id.btn_open_ActivityA).setOnClickListener {
startActivity(Intent(this, ActivityA::class.java))
}

// Реализуйте кнопки перехода в активити с фрагментами в MainActivity.
findViewById<Button>(R.id.btn_open_ActivityB).setOnClickListener {
startActivity(Intent(this, ActivityB::class.java))
}
}
}
22 changes: 22 additions & 0 deletions app/src/main/res/layout/activity_a.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".ActivityA">

<TextView
android:id="@+id/textView3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Activity A"
android:textAppearance="@style/TextAppearance.AppCompat.Large" />

<androidx.fragment.app.FragmentContainerView
android:id="@+id/container_FragmentA"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/transparent" />

</LinearLayout>
22 changes: 22 additions & 0 deletions app/src/main/res/layout/activity_b.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ActivityB">

<androidx.fragment.app.FragmentContainerView
android:id="@+id/frameLayout_ba"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
/>

<androidx.fragment.app.FragmentContainerView
android:id="@+id/frameLayout_bb"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
/>

</LinearLayout>
Loading