클라이언트

Fragment 간의 데이터 전달 및 findViewById 사용하기

애기공룡훈련병 2019. 6. 10. 15:16
반응형

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

 

반응형