Android studio-Fragmentに関して


Fragmentに関して昔の教則動画を見たら、またいろいろと更新されたようで、ここで記録しておきます。

Import fragment package 


package com.example.fragment;

import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class TopSectionFragment extends Fragment{

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        //convert xml file to View object; parent=parameter ViewGroup container of the method
        //you can use layoutInflater directly with the parameter of inflater
        View view=inflater.inflate(R.layout.top_section_fragment,container,false);
        return super.onCreateView(inflater, container, savedInstanceState);
    }
}

まずFragmentのインポートルートは上記になりました。
Androidxに移転したSupport系のパッケージはこちらのリンクで調べてみてください。
https://developer.android.com/jetpack/androidx/migrate/artifact-mappings

Androidxへの乗り換えに関しました。下記リンクで説明が見られます。
https://developer.android.com/jetpack/androidx/migrate

FragmentをActvityでpreviewしたい場合

Android studio 3.x verから直接Fragmentをプレビューできなくなったようで、
Actvityのxmlにtools:layout=を入れないといけません。


 <!--adding tools:layout=@layout/fragmentXmlFileName to preview the fragment-->

    <fragment
        android:id="@+id/fragment3"
        android:name="com.example.fragment.TopSectionFragment"
        android:layout_width="350dp"
        android:layout_height="200dp"
        android:layout_marginStart="28dp"
        android:layout_marginTop="16dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:layout="@layout/top_section_fragment" />

以上は覚書です。