1 Activity
Activityは、Fragmentを入れる入れ物のようなもので、紙芝居の外枠のようなもの
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.add(R.id.container, new FirstFragment());
transaction.commit();
}
}
}
2 1つ目のFragment
public class FirstFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_first, container, false);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Button btn1 = view.findViewById(R.id.button1);
btn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
FragmentManager fragmentManager = getFragmentManager();
if(fragmentManager != null){
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
// BackStackを設定
fragmentTransaction.addToBackStack(null);
fragmentTransaction.replace(R.id.container, new SecondFragment());
fragmentTransaction.commit();
}
}
});
}
}
ボタンを押すと、2つめのFragmentに画面遷移します。
3 SecondFragment
public class SecondFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_second, container, false);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Button btn2 = view.findViewById(R.id.button2);
btn2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 1つ前に戻る
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.popBackStack();
}
});
}
}