目的
Activity
やFragment
からFragment
を呼ぶときの実装メモ
実装方法
ソースコード
以下のように簡単なActivity
とFragment
2つを作りました。
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button activityButton = findViewById(R.id.button);
activityButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
FragmentManager fragmentManager = getSupportFragmentManager();
if(fragmentManager != null) {
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.addToBackStack(null);
fragmentTransaction.replace(R.id.content1, Fragment1.newInstance());
fragmentTransaction.commit();
}
}
});
}
}
public class Fragment1 extends Fragment {
public static Fragment1 newInstance(){
//インスタンス生成
Fragment1 category = new Fragment1();
return category;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View fragment1 = inflater.inflate(R.layout.fragment1, container, false);
return fragment1;
}
@Override
public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Button fragment1Button = view.findViewById(R.id.button1);
fragment1Button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
FragmentManager fragmentManager = getChildFragmentManager();
if(fragmentManager != null) {
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.contentFragment1, Fragment2.newInstance());
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
}
});
}
}
public class Fragment2 extends Fragment {
public static Fragment2 newInstance(){
//インスタンス生成
Fragment2 category = new Fragment2();
return category;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View fragment2 = inflater.inflate(R.layout.fragment2, container, false);
return fragment2;
}
}
レイアウトXmlファイルは以下のようなものとしました。
Fragmentもほぼ一緒なので省略します。
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/content1"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FF5722">
<Button
android:id="@+id/button"
android:layout_width="120dp"
android:layout_height="wrap_content"
android:text="Activity"
android:layout_centerInParent="true"
/>
</RelativeLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
実行結果
その他気になったこと
Fragment1からFragment2を呼ぶ時、
getFragmentManager
としていますが、うまく行かない時はgetChildFragmentManager
と
したほうが良いかもしれません。