要使用 Fragment 在 dependency import
dependencies {
implementation "androidx.navigation:navigation-fragment-ktx:2.3.0"
}
Fragment 二種方式使用
**定義在 xml **
*MainActivity *
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
}
activitymain.xml 改成 fragment
<?xml version="1.0" encoding="utf-8"?>
<navigation 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:id="@+id/nav_graph.xml"
app:startDestination="@id/mainFragment">
<fragment
android:id="@+id/mainFragment"
android:name="tw.andyang.kotlinandroidworkshop.TodoListFragment"
tools:layout="@layout/fragment_todo_list" />
</navigation>
create TodoListFragment fragment
class TodoListFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_todo_list, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
}
}
*create TodoListFragment 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"
android:clipToPadding="false"
tools:context=".TodoListFragment">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="60dp"
tools:listitem="@layout/item_todo" />
<androidx.appcompat.widget.AppCompatButton
android:id="@+id/buttonAdd"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/add_todo"
app:layout_constraintBottom_toBottomOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
FragmentManager
FragmentManager:
管理Activity中的fragments,通過呼叫getFragmentManager() | getSupportFragmentManager()獲取FragmentManager
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Fragment Transactions:
使用Fragment時,通過使用者互動來執行如增加、移除、替換等。
// 建立 Fragment
Fragment newFragment = new testFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
transaction.commit();
newFragment將取代在R.id.fragment_container fragment。如果本身沒有就直接新增新的fragment。
呼叫addToBackStack(),最後commit()被儲存在back stack中,按Back鍵可以返回上一個轉換前的狀態。
Fragment的replace、add、hide、show 說明
reference :https://ithelp.ithome.com.tw/articles/10221199