[안드로이드] navigation drawer에서 fragment를 사용해 화면전환을 하고싶은데요..

조회수 2878회

public boolean onNavigationItemSelected(MenuItem item) { // Handle navigation view item clicks here. int id = item.getItemId();

    Fragment fragment = null;
    String title = getString(R.string.app_name);

    if (id == R.id.nav_camera) {
        // Handle the camera action
        fragment = new HomeFragment();
        title = "Homes";
    } else if (id == R.id.nav_gallery) {
        fragment = new SettingFragment();
        title = "Settings";
    } else if (id == R.id.nav_slideshow) {

    } else if (id == R.id.nav_manage) {

    } else if (id == R.id.nav_share) {

    } else if (id == R.id.nav_send) {

    }
    if (fragment != null) {
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.replace(R.id.content_fragment_layout, fragment);
        ft.commit();
    }

    // set the toolbar title
    if (getSupportActionBar() != null) {
        getSupportActionBar().setTitle(title);
    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);

    return true;
}

}

Mainactivity에서 구현한 코드인데 item을 눌렀을때 생성한fragement로 넘어가고자 했습니다. 근데

if (id == R.id.nav_camera) { // Handle the camera action fragment = new HomeFragment(); title = "Homes"; } else if (id == R.id.nav_gallery) ``{ fragment = new SettingFragment(); title = "Settings"; 이부분의 new HomeFragment();와 SettingFragment(); 에서 빨간줄이 그어지는데 이유를 모르겠습니다.

  • (•́ ✖ •̀)
    알 수 없는 사용자
  • 빨간줄이 그어지는곳에 마우스를 대면 에러이유가 나오는데 에러이유를 올려주시면 대답하는 분들이 더 편할것 같습니다. 알 수 없는 사용자 2016.11.25 23:49

1 답변

  • 경험에 의해 문제 현상에 대해 답변드리면 FragmentActivity에서 참조하는 Fragment와 HomeFragment/SettingFragment에서 참조하는 Fragment가 서로 다른것으로 추측됩니다.

    올려주신 코드에서는 import 되어있는 부분 확인하시면 android.support.v4.app.fragment로 되어있는지 확인이 필요할것 같고요 HomeFragment/SettingFragment 내용도 마찬가지로 import 되어있는 부분이 android.support.v4.app.fragment로 되어있는지 확인 해보심이 좋을것 같네요

    Fragment를 사용하실때 android.support.v4.app.fragment와 android.app.Fragment를 통일해서 사용해야 Error 없이 사용 가능합니다.

    • (•́ ✖ •̀)
      알 수 없는 사용자

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)