Fragment 사용법

android 2020. 2. 1. 17:02

* 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 안에 추가

'android' 카테고리의 다른 글

ActionBar - 옵션 메뉴  (0) 2020.02.02
Fragment 인터페이스  (0) 2020.02.02
SharedPreferences 사용법  (0) 2020.02.01
Intent 값전달 및 받기  (0) 2020.02.01
Intent 사용법  (0) 2020.02.01
블로그 이미지

디츠

“말은 쉽지, 코드를 보여줘.” “Talk is cheap. Show me the code.” – 리누스 토르발스(Linus Torvalds)

,