ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Fragment를 이용한 TabActivity
    Android 2012. 11. 9. 17:57

    MainActivity.java

    package com.example.hellotabfragment;
    
    import java.util.HashMap;
    
    import android.content.Context;
    import android.os.Bundle;
    import android.support.v4.app.Fragment;
    import android.support.v4.app.FragmentActivity;
    import android.support.v4.app.FragmentTransaction;
    import android.util.Log;
    import android.view.View;
    import android.widget.TabHost;
    
    import com.example.hellotabfragment.fragment.Fragment1;
    import com.example.hellotabfragment.fragment.Fragment2;
    import com.example.hellotabfragment.fragment.Fragment3;
    
    /**
     * This demonstrates how you can implement switching between the tabs of a
     * TabHost through fragments.  It uses a trick (see the code below) to allow
     * the tabs to switch between fragments instead of simple views.
     */
    public class MainActivity extends FragmentActivity {
        TabHost mTabHost;
        TabManager mTabManager;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            setContentView(R.layout.activity_main);
            mTabHost = (TabHost)findViewById(android.R.id.tabhost);//Container for a tabbed window view.
            mTabHost.setup();
    
            mTabManager = new TabManager(this, mTabHost, R.id.realtabcontent);// tab host와 탭을 눌렀을때 바뀌어야하는 부분의 id
            mTabManager.addTab(mTabHost.newTabSpec("simple").setIndicator("Simple"), Fragment1.class, null);	//새로운 탭을 만든다.
            //tabspec -> A tab has a tab indicator, content, and a tag that is used to keep track of it
            mTabManager.addTab(mTabHost.newTabSpec("contacts").setIndicator("Contacts"), Fragment2.class, null);
            mTabManager.addTab(mTabHost.newTabSpec("custom").setIndicator("Custom"), Fragment3.class, null);
    
    
            if (savedInstanceState != null) {
                mTabHost.setCurrentTabByTag(savedInstanceState.getString("tab"));	// 방향 전환 전에 선택된 탭이 있다면 가져와서 설정
            }
        }
    
        @Override
        protected void onSaveInstanceState(Bundle outState) {
            super.onSaveInstanceState(outState);
            outState.putString("tab", mTabHost.getCurrentTabTag());	// 방향 전환될때 넣어준다.
            Log.e("tab", mTabHost.getCurrentTabTag());
        }
    
        /**
         * This is a helper class that implements a generic mechanism for
         * associating fragments with the tabs in a tab host.  It relies on a
         * trick.  Normally a tab host has a simple API for supplying a View or
         * Intent that each tab will show.  This is not sufficient for switching
         * between fragments.  So instead we make the content part of the tab host
         * 0dp high (it is not shown) and the TabManager supplies its own dummy
         * view to show as the tab content.  It listens to changes in tabs, and takes
         * care of switch to the correct fragment shown in a separate content area
         * whenever the selected tab changes.
         */
        public static class TabManager implements TabHost.OnTabChangeListener {
            private final FragmentActivity mActivity;	//context
            private final TabHost mTabHost;
            private final int mContainerId;	
            private final HashMap mTabs = new HashMap();	// tag기준으로 tab에대한 정보가 들어있다.
            TabInfo mLastTab;
    
            static final class TabInfo {
                private final String tag;
                private final Class clss;
                private final Bundle args;
                private Fragment fragment;
    
                TabInfo(String _tag, Class _class, Bundle _args) {
                    tag = _tag;
                    clss = _class;
                    args = _args;
                }
            }
    
            static class DummyTabFactory implements TabHost.TabContentFactory{ // Makes the content of a tab when it is selected. 
            	// 굳이 필요 없어 보이는 듯
                private final Context mContext;
    
                public DummyTabFactory(Context context) {
                    mContext = context;
                }
    
                @Override
                public View createTabContent(String tag) {
                    View v = new View(mContext);
                    v.setMinimumWidth(0);
                    v.setMinimumHeight(0);
                    return v;
                }
            }
    
            public TabManager(FragmentActivity activity, TabHost tabHost, int containerId) {
                mActivity = activity;
                mTabHost = tabHost;
                mContainerId = containerId;
                mTabHost.setOnTabChangedListener(this);
            }
    
            public void addTab(TabHost.TabSpec tabSpec, Class clss, Bundle args) {	// tab추가하기
                tabSpec.setContent(new DummyTabFactory(mActivity));
                String tag = tabSpec.getTag();
    
                TabInfo info = new TabInfo(tag, clss, args);	// 그닥 필요없어 보이긴함
    
                // Check to see if we already have a fragment for this tab, probably
                // from a previously saved state.  If so, deactivate it, because our
                // initial state is that a tab isn't shown.
                info.fragment = mActivity.getSupportFragmentManager().findFragmentByTag(tag);	//tag로 프래그먼트 찾아서 넣어준다.
                if (info.fragment != null && !info.fragment.isDetached()) {	//frament가 null이아니고 떨어져있지 않으면 떼준다.
                	
                    FragmentTransaction ft = mActivity.getSupportFragmentManager().beginTransaction();
                    ft.detach(info.fragment);
                    ft.commit();
                }
    
                mTabs.put(tag, info);	//자료형에 넣어준다. 이것도 불필요함
                mTabHost.addTab(tabSpec);	// 탭호스트에 실제로 탭을 넣어준다.
            }
    
            @Override
            public void onTabChanged(String tabId) {
                TabInfo newTab = mTabs.get(tabId);	// 넣어놨던 tabinfo찾아온다.
                if (mLastTab != newTab) {//라스트탭이 뉴탭과 같지 않다면
                    FragmentTransaction ft = mActivity.getSupportFragmentManager().beginTransaction();
                    if (mLastTab != null) {	//라스트탭이 널이 아니면
                        if (mLastTab.fragment != null) {	//라스트탭의 프래그먼트가 널이 아니면
                            ft.detach(mLastTab.fragment);	//떼어낸다
                        }
                    }
                    if (newTab != null) {	// 뉴탭이 널이 아니면
                        if (newTab.fragment == null) {	//프래그먼트가 널이면
                            newTab.fragment = Fragment.instantiate(mActivity,
                                    newTab.clss.getName(), newTab.args);//새로 만들어준다
                            ft.add(mContainerId, newTab.fragment, newTab.tag);	//추가해준다
                        } else {
                            ft.attach(newTab.fragment);	//널이 아니면 그대로 붙여준다.
                        }
                    }
    
                    mLastTab = newTab;	//새로운탭이 라스트탭이 된다.
                    ft.commit();
                    mActivity.getSupportFragmentManager().executePendingTransactions();
                }
            }
        }
    }
    
    activity_main.xml
    
    
        
    
            
    
            
    
            
        
    
    
    
    


    'Android' 카테고리의 다른 글

    fragment에서 attach, detach method!  (0) 2012.11.12
    Fragment 에서 방향 전환시 null 체크  (0) 2012.11.09
    Fragment(1)  (0) 2012.11.09
    생명주기 메소드를 Override할때 super의 위치  (0) 2012.11.08
    IntentService  (0) 2012.11.06
Designed by Tistory.