Fragmentの使い方まとめ。
・ActivityにFragmentを表示させる手順
・Activityクラス
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
}
・Fragmentクラス
class ListFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.fragment_list, container, false)
return view
}
}
・activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
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"
android:orientation="vertical" >
<fragment
android:id="@+id/list_fragment"
android:name="com.example.android_simple_memo.fragment.ListFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
・fragment_list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinerLayout
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"
android:orientation="vertical"
tools:context=".fragment.ListFragment" >
<EditText
android:id="@+id/hello_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="hello fragment" />
</LinerLayout>
ActivityにFragmentを表示する際は、Activityのxmlファイルに<fragment></fragment>タグを埋め込む。