Fragment 인터페이스

android 2020. 2. 2. 15:02

* MainActivity.java

public class MainActivity extends AppCompatActivity implements Common {

    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();
    }

    @Override
    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();
        }
    }
}

* Common Interface.java

public interface Common {
    public void onFragmentChanged(int index);
}

* MainFragment.java

public class MainFragment extends Fragment {

    Common common;

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);

        if (context instanceof Common) {
            common = (Common) context;
        }
    }

    @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) {
                common.onFragmentChanged(1);
            }
        });

        return rootView;
    }

}

* MenuFragment.java

public class MenuFragment extends Fragment {

    Common common;

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);

        if (context instanceof Common) {
            common = (Common) context;
        }
    }

    @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) {
                common.onFragmentChanged(1);
            }
        });

        return rootView;
    }

}

'android' 카테고리의 다른 글

ActionBar - Home 아이콘 변경  (0) 2020.02.02
ActionBar - 옵션 메뉴  (0) 2020.02.02
Fragment 사용법  (0) 2020.02.01
SharedPreferences 사용법  (0) 2020.02.01
Intent 값전달 및 받기  (0) 2020.02.01
블로그 이미지

디츠

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

,