* Fragment 추가 : New > Fragment > Fragment(Blank) > activity_main.xml 내용 추가
<fragment
android:id="@+id/mainFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="com.example.fragment.MainFragment" />
* MainActivity.java
public class MainActivity extends AppCompatActivity {
MainFragment mainFragment;
MenuFragment menuFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainFragment = (MainFragment) getSupportFragmentManager().findFragmentById(R.id.mainFragment);
menuFragment = new MenuFragment();
}
public void onFragmentChanged(int index) {
if (index == 0) {
getSupportFragmentManager().beginTransaction().replace(R.id.container, mainFragment).commit();
} else if (index == 1) {
getSupportFragmentManager().beginTransaction().replace(R.id.container, menuFragment).commit();
}
}
}
* MainFragment.java
public class MainFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_main, container, false);
Button button = rootView.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
MainActivity activity = (MainActivity) getActivity();
activity.onFragmentChanged(1);
}
});
return rootView;
}
}
* MenuFragment.java
public class MenuFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_menu, container, false);
Button button = rootView.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
MainActivity activity = (MainActivity) getActivity();
activity.onFragmentChanged(0);
}
});
return rootView;
}
}
* 주의사항 : Fragment는 FrameLayout 안에 추가