ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 프래그먼트 사용해보기
    안드로이드/학습&강좌 2015. 6. 4. 15:55

    요새들어 개발추세가 액티비티 구조의 대부분의 앱들이 프래그먼트 형태로 리뉴얼 또는 신규 출시 되는 구조라 생각된다.


    예전에 개발할때는 액티비티위주로 개발함에 따라 UI가 어느정도 제약사항이 있었는데( 뭐.. 클라이언트가 원한다면 구현하겠지만;;;) 


    신규 컴퍼넌트 Fragment 의 등장에 따라 앱시장이 많이 요동치고 있는건 사실인거 같다..( 개인적으로 느끼기엔;)


    프래그먼트 Reference 문서 

    http://developer.android.com/reference/android/app/Fragment.html


    3.0 이상의 SDK 에서는 기본적으로 사용 가능하지만 기존 앱버전을 지원하려면 

    android-support-v4.jar 파일을 추가 해주면된다.


    기본적인 라이프사이클구조는


    Lifecycle

    Though a Fragment's lifecycle is tied to its owning activity, it has its own wrinkle on the standard activity lifecycle. It includes basic activity lifecycle methods such as onResume(), but also important are methods related to interactions with the activity and UI generation.

    The core series of lifecycle methods that are called to bring a fragment up to resumed state (interacting with the user) are:

    1. onAttach(Activity) called once the fragment is associated with its activity.
    2. onCreate(Bundle) called to do initial creation of the fragment.
    3. onCreateView(LayoutInflater, ViewGroup, Bundle) creates and returns the view hierarchy associated with the fragment.
    4. onActivityCreated(Bundle) tells the fragment that its activity has completed its own Activity.onCreate().
    5. onViewStateRestored(Bundle) tells the fragment that all of the saved state of its view hierarchy has been restored.
    6. onStart() makes the fragment visible to the user (based on its containing activity being started).
    7. onResume() makes the fragment begin interacting with the user (based on its containing activity being resumed).

    As a fragment is no longer being used, it goes through a reverse series of callbacks:

    1. onPause() fragment is no longer interacting with the user either because its activity is being paused or a fragment operation is modifying it in the activity.
    2. onStop() fragment is no longer visible to the user either because its activity is being stopped or a fragment operation is modifying it in the activity.
    3. onDestroyView() allows the fragment to clean up resources associated with its View.
    4. onDestroy() called to do final cleanup of the fragment's state.
    5. onDetach() called immediately prior to the fragment no longer being associated with its activity.



    위와 같이 설명되어있는데 액티비티와 상당히 유사하며, 자신의 속한 액티비티에 종속적이다. 라고 나와있다.


    이론설명은 여기까지만 하고, 


    1.기본적인 Tab Activity 같은 모양의 형태와 

    2. ViewPager 연동

    3. Navigation Drawer 연동을 작성해 볼 예정이다.


    구현해볼 사항은 



    기본적인 버튼 세개와 버튼을 눌럿을 경우 새로운 프래그먼트 생성으로 만들어 볼 생각이다.


    메인 Activity 



    public class MainActivity extends FragmentActivity implements OnClickListener{
    	Button mBtn01, mBtn02, mBtn03; //프래그먼트 이동 버튼
    	
    	Fragment frReplaceFragment = null;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            
            mBtn01 = (Button)findViewById(R.id.btn_01);
            mBtn01.setTag(1);
            
            mBtn02 = (Button)findViewById(R.id.btn_02);
            mBtn02.setTag(2);
            
            mBtn03 = (Button)findViewById(R.id.btn_03);
            mBtn03.setTag(3);
            
            mBtn01.setOnClickListener(this);
            mBtn02.setOnClickListener(this);
            mBtn03.setOnClickListener(this);
            
            setFragmentChange(1);
        }
        
        @Override
        public void onClick(View v) {
        	
        	Log.d(">> ",  "" + (Integer)v.getTag());
        	switch (v.getId()) {
        	
    		case R.id.btn_01:
    			Toast.makeText(this, "01", Toast.LENGTH_SHORT).show();
    			setFragmentChange((Integer)v.getTag());
    			break;
    			
    		case R.id.btn_02:
    //			frReplaceFragment = new SecondFragment();
    			setFragmentChange((Integer)v.getTag());
    			break;
    			
    		case R.id.btn_03:
    //			frReplaceFragment = new ThirdFirstFragment();
    			setFragmentChange((Integer)v.getTag());
    			break;
    			
    
    		}
        	
        }
        
        //프래그먼트 이동
        public void setFragmentChange(int fragmentIdx){
        	Log.d(">>>>", "FragmentIdx : " + fragmentIdx);
        	switch (fragmentIdx) {
    		case 1:
    			frReplaceFragment = new FirstFragment();
    			break;
    		case 2:
    			frReplaceFragment = new SecondFragment();
    			break;
    		case 3:
    			frReplaceFragment = new ThirdFirstFragment();
    			break;
    
    		default:
    			break;
    		}
    
    
    		// replace fragment
    		final FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    		transaction.replace(R.id.target_fragment, frReplaceFragment);
    		
    		//Fragment Stack 추가
    //		transaction.addToBackStack(null);
    
    		// Commit the transaction
    		transaction.commit();
        }
    
    }
    

    FragmentActivity를 사용해서 기존 Activity같이 작성하면 된다.


    Xml 에서는 Fragment 를 띄울 영역을 미리 지정해 준다. 

    이 방식은 ViewPager 에서의 방식과는 다른데 다음 포스팅에서 보도록 하자.




    
    
        
    
            
    
                
    기본적인 버튼 3개와 영역 분기가 전부...

    프래그먼트 Java 소스는 inflater 를 이용한  ui 전달이 전부이다.






    public class FirstFragment extends Fragment{
    	
    	@Override
    	public View onCreateView(LayoutInflater inflater, ViewGroup container,
    			Bundle savedInstanceState) {
    		View view = inflater.inflate(R.layout.fragment01, null);
    		return view;
    	}
    }
    
    

    Fragment xml 은 생략하도록 하겠다. TextView 하나 넣어논게 전부라서..


    정말 간단하게 프래그먼트 개념이해차 만들어본 소스이다.


    다음에 지금 버튼으로 동작하는 Fragment 를 Swipe 방식을 이용해서 구현해 보자~



    FragmentTest.zip


    소스는 댓글 후 다운로드 해주세요 ~ (__)


    댓글

COPYRIGHT 2010 EpoNg. ALL RIGHTS RESERVED.