티스토리 뷰

UI 상으로 CommentActivity 와 그 하위에 CommentListFragment 가 있다고 가정한다.

public static class CommentListFragment extends SherlockListFragment {
    private String mNum;

    /**
     * Create a new instance of CommentFragment, providing "num" as an argument.
     * CommentListFragment list = CommentListFragment.newInstance(num);
     */
    public static CommentListFragment newInstance(String sNum) {
        CommentListFragment f = new CommentListFragment();

        // Supply num input as an argument.
        Bundle args = new Bundle();
        args.putString("num", sNum);
        f.setArguments(args);

        return f;
    }
    
    public void setNum(String sNum) {
        this.mNum = sNum;
    }
    
    private String getNum() {
        return  getArguments().getString("num");
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        
        this.mNum = getNum();
        
        if (this.mNum == null || this.mNum.length() == 0) {
            getActivity().finish();
            //getActivity().getSupportFragmentManager().beginTransaction().remove(this).commit();
        }
        ......
    }
}

데이터 전달 방법#1

public class CommentActivity extends SherlockFragmentActivity {
    private String num = "";
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        // FragmentManager를 받아온다.
        FragmentManager fm = getSupportFragmentManager();
        // findFragmentById(android.R.id.content) = 루트뷰
        if (fm.findFragmentById(android.R.id.content) == null) {
        	// 리스트로 사용할 MainListFragment 생성
        	CommentListFragment list = CommentListFragment.newInstance(num);
        	// FragmentTransaction 시작하고 액티비티에 붙이고 변경사항을 적용
        	FragmentTransaction ft = fm.beginTransaction();
        	//ft.addToBackStack(null); // 물리 Back 버튼 누르면 현 Fragment를 finish()
        	ft.add(android.R.id.content, list).commit();
        }
    }
}

데이터 전달 방법#2

public class CommentActivity extends SherlockFragmentActivity {
    private String num = "";
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        // FragmentManager를 받아온다.
        FragmentManager fm = getSupportFragmentManager();
        // findFragmentById(android.R.id.content) = 루트뷰
        if (fm.findFragmentById(android.R.id.content) == null) {
        	// 리스트로 사용할 MainListFragment 생성
        	CommentListFragment list = new CommentListFragment();
        	list.setNum(num);        	
        	// FragmentTransaction 시작하고 액티비티에 붙이고 변경사항을 적용
        	FragmentTransaction ft = fm.beginTransaction();
        	//ft.addToBackStack(null); // 물리 Back 버튼 누르면 현 Fragment를 finish()
        	ft.add(android.R.id.content, list).commit();
        }
    }
}

참고 = http://marakana.com/s/post/1250/android_fragments_tutorial

댓글