티스토리 뷰

반응형
SMALL

안드로이드에서 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;
    }
    ...
}

 

반응형
LIST
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함