在快速建立完預設的Fragment後
我們就能把Fragment編入Activity中
但是我的Fragment同樣擁有自己的layout
於是呢和Activity不同的是
我不會在onCreate()調用回去
而是在onCreateView(),return 我們這次編排的layout
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_main, container, false)
}
當中的R.layout.fragment_main
就是我們快速建立Fragment時產生的Layout
利用到我們前幾篇介紹的ConstraintLayout去編排
設置一個區塊放置我們的Fragment
<?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">
<TextView
android:id="@+id/textView"
android:layout_marginTop="50dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello MainActivity!"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<androidx.constraintlayout.widget.ConstraintLayout
android:id="@+id/fragment"
android:layout_width="match_parent"
android:layout_height="500dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView"
android:background="@color/colorAccent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
Log.d("Activity","onCreate")
val newFragment = MainFragment()
val transaction = supportFragmentManager.beginTransaction()
transaction.replace(R.id.fragment, newFragment)
transaction.addToBackStack(null)
transaction.commit()
}