카테고리 없음

프래그먼트에서 액티비티 메소드 호출하기

장꾸꾸 2020. 10. 8. 10:48

메뉴화면을 프래그먼트로 빼준다.
메뉴 프래그먼트 -> 프래그먼트 edit/ 프래그먼트 study로 이동한 모습

 

MainActivity 의 change 메소드

    public void change(int type){

        //TODO 프래그먼트 안에 아래 4줄 코드가 들어가면 X 메소드로 따로 빼서 해야함
//    FragmentManager fm = getSupportFragmentManager();
//    FragmentTransaction ft = fm.beginTransaction();
//            ft.replace(R.id.body_rl, fragmentE);
//            ft.commit();
// 메소드/ 변수 소문자로 시작

        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        if(type == 0){
            ft.replace(R.id.body_rl, fragmentE);
            ft.commit();
        }else if(type == 1){
            ft.replace(R.id.body_rl, fragmentS);
            ft.commit();
        }else{
            finish();
        }

    }

 

FragmentM

    @Override
    //TODO 프래그먼트에서 액티비티 메소드 호출 (change 호출)
    public void onClick(View v) {
        if (v.getId() == R.id.bt_edit) {
//            Intent intent = new Intent(this, my.real.voca.EditActivity.class);
//            startActivity(new Intent(this, com.example.ex_voca.EditActivity.class));
//            startActivity(intent);
//           액티비티말고 프래그먼트로 바꿔주기
            ((MainActivity)getActivity()).change(0);

        } else if (v.getId() == R.id.bt_study) {
//     startActivity(new Intent(this, com.example.ex_voca.StudyActivity.class));
            ((MainActivity)getActivity()).change(1);

        } else if (v.getId() == R.id.bt_quit) {
 //피니시는 액티비티 용이니까 접근할 수 있도록 바꿔줘야 함
            ((MainActivity)getActivity()).change(3456);
        }
    }

 

yongyi1587.tistory.com/10

 

[Android] Fragment에서 Activity Method 사용하기

Fragment에서 Activity의 method를 사용하는 법입니다. 간단한 예제로 설명하겠습니다. MainActivity.java public class MainActivity extends AppCompatActivity { ... private Button btn; ... public void test..

yongyi1587.tistory.com