반응형
안드로이드에서 Fragment 간에 데이터를 전달하는 방법에 대해서 정리하고자 한다.
Activity에서는 Intent를 사용하여 데이터를 전달한다면 Fragment는 Bundle을 사용하면 된다.
Fragment fragment = new testFragment(); // Fragment 생성
Bundle bundle = new Bundle();
bundle.putString("param1", param1); // Key, Value
bundle.putString("param2", param2); // Key, Value
fragment.setArguments(bundle);
Bundle로 전달된 데이터는 전달받는 Fragment의 onCreateView에서 getArguments()를 이용하여
데이터를 가져올 수 있다.
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
if(getArguments() != null) {
String param1 = getArguments().getString("param1"); // 전달한 key 값
String param2 = getArguments().getString("param2"); // 전달한 key 값
}
return inflater.inflate(R.layout.test_fragment, null);
}
Fragment에서 findViewById에서 문제가 생기지 않도록 하려면 어떻게 해야할까?
getView() 메서드를 통해서도 해결 할 수 있지만 Fragment onCreateView함수에서 View 객체에 현재 View에 가져와
그 View에서 원하는 컴포넌트를 찾으면 해결된다.
public class TabFramgent extends Fragment {
...
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_tab_framgent, container, false);
TextView txtId = (TextView)v.findViewById(R.id.txtId);
return v;
}
...
}
반응형
'클라이언트' 카테고리의 다른 글
Android Context에 대하여 (0) | 2019.06.10 |
---|---|
Activity의 4가지 Launch Mode에 대하여 (0) | 2019.06.10 |
Retrofit2 사용해보기 (0) | 2019.05.31 |
ANR의 정의, 발생 요인 및 대응책 (0) | 2019.05.30 |
High Resolution Bitmap를 ImageView에 적용 시 Bitmap Error를 해결하는 방법 (0) | 2019.05.30 |