posted by Kyleslab 2012. 11. 9. 15:42

개인적인 생각으로 Fragment는 객체화시킬수 있는 서브 액티비티라는 생각이다. 

액티비티자체는 객체화 시킬수 없어 사용에 불편함이 있다. 

그러나 프래그먼트는 객체화가 가능하여 유연성있게 사용할 수 있다. 그리고 단독으로는 사용할 수 없다. 액티비티안에 사용할 수 있다.

액티비티 끼리는 인텐트를 주고받지만 프래그먼트는 argument로 값을 주고 받는다.

그런데 프래그먼트를 생성할때마다 Bundle을 만들어 아규먼트를 전달 받고 전달하는 것은 낭비라는 생각이 들어 메소드를 만든다.

static TextFragment newInstance(String _msg){
		TextFragment tf = new TextFragment();
		Bundle bundle = new Bundle();
		bundle.putString("msg", _msg);
		tf.setArguments(bundle);

		return tf;
	}

	public String getMsg(){
		if(getArguments().getString("msg")!=null){
			return getArguments().getString("msg");
		}
		return "msg";
	}


이런 식으로 메소드를 만들고 실제로 Fragment 객체를 생성할때는 new가 아닌

TextFragment tf = TextFragment.newInstance(((TextView)v).getText().toString());

이런 식으로 메소드를 호출하여 사용한다.

new로 생성하는 것외에 Fragment 에서 자체적으로 지원해주는 메소드도 있다. new로 생성하는 것과 차이는 없지만

인스턴스화가 실패했을 경우 에러 처리를 해준다.

public static Fragment instantiate (Context context, String fname, Bundle args)

Added in API level 11

Create a new instance of a Fragment with the given class name. This is the same as calling its empty constructor.

Parameters
contextThe calling context being used to instantiate the fragment. This is currently just used to get its ClassLoader.
fnameThe class name of the fragment to instantiate.
argsBundle of arguments to supply to the fragment, which it can retrieve with getArguments(). May be null.
Returns
  • Returns a new fragment instance.
Throws
InstantiationExceptionIf there is a failure in instantiating the given fragment class. This is a runtime exception; it is not normally expected to happen.



'Mobile > Android' 카테고리의 다른 글

Fragment 에서 방향 전환시 null 체크  (0) 2012.11.09
Fragment를 이용한 TabActivity  (0) 2012.11.09
생명주기 메소드를 Override할때 super의 위치  (0) 2012.11.08
IntentService  (0) 2012.11.06
weight값설정시 최적화  (0) 2012.11.06