건프의 소소한 개발이야기

[안드로이드] Android NavigationView - Fragment 화면전환까지 본문

개발 이야기/안드로이드 이야기

[안드로이드] Android NavigationView - Fragment 화면전환까지

건강한프로그래머 2016. 4. 19. 11:14

안녕하세요, 건프입니다.


앞에서 구글의 어플리케이션 디자인 패턴(Material Design) 의 한 축을 이루는 NavigationView 를 이용해서 구조를 살펴보았습니다.

구조를 알았으니, 안에 있는 내용물을 바꾸는(화면 전환) 작업은 쉬울 꺼라고 생각했는데.....!!


막상 해보니까 레퍼런스도 아직 많이 없고(Navigation View가 없던시절 ListView로 대리만족했던 시절의 레퍼런스들이 많더라구요)

게다가, 어이없는 부분에서 심한 삽질 및 고생을 해서... 이렇게 추가 포스팅을 올립니다.


이전 포스팅에서 NavigationViewListener 가 다음과 같이 세팅되어 있엇죠.

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

if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {

} 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) {

}

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

즉, 아이템이 선택됨에 따라, 움직이는 분기를 우리가 조절할 수 있었습니다.


그럼 이제 여기에서 Fragment 간 화면전환을 적용하면 됩니다. 어떻게 하느냐.


저는 일단 이렇게 구성해보았습니다.

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

예시로 두개의 간단한 Fragment 클래스를 정의해두고, 위와 같이 분기합니다. 

FragmentTransaction 클래스를 이용해서, NavigationView Item Click 이벤트마다 replace 해주면 됩니다.


그렇다면 저기에 있는 R.id.content_fragment_layout 은 무엇인지 확인할께요

content_main.xml 

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context=".ui.MainActivity"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:showIn="@layout/app_bar_main">

<FrameLayout
android:id="@+id/content_fragment_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" />

</RelativeLayout>

바로 여기입니다. 

파일 구조는 이전 포스팅에도 실려있지만, 굳이 한번 정리하자면

activity_main.xml     (--include-->)     app_bar_main.xml     (--include-->)     content_main.xml 

요렇게 되어 있습니다.

주의!

위의 코드의 app:layout_behavior="@string/appbar_scrolling_view_behavior"

부분을 제가 실수로 삭제했더니,

화면에 들어가야하는 텍스트가, appbar 아래부터 위치하는 것이 아니라, appbar가 있는 부분을 무시하고 appbar위치부터 겹쳐서 나와 이상하게 됩니다..

(이걸 몰라서 처음부터해서 갈아끼우는 Fragment들도 모두 appbar를 무시해서 완전 이상하게 화면이 랜더링 됩니다...이 문제인지 모르고 FrameLayout을 Linear, Relative, Fragment 바꾸고 난리치고... 엄청 삽질함)


네 이렇게 하시고

크게 중요해보이지는 않지만 예시 Fragment는 다음과 같이 작성했습니다.

public class HomeFragment extends Fragment {


public HomeFragment() {
// Required empty public constructor
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_home, container, false);
}

}


자 이렇게 하면, NavigationView 에서 Item 을 선택했을때, 해당 아이템에 관한 화면으로 넘어가게 만드는 것을 만들 수 있습니다.


너무 당연하고 쉬운 코드일 수 있어도 개인적으로 저는 꽤 오랜시간 삽질을 한 터라.. 작은 도움이라도 되길 바라면서 올립니다.


고맙습니다 :)


Comments