Fragment(碎片)

Fragment表示「碎片」,它的設計理念是將Activity劃分爲不一樣的區塊,各區塊能夠是某個控件,也能夠是由Fragment實現顯示的部分。
【基本特性】
1. 能夠在佈局中添加某個容器承載Fragment,具體的顯示內容由Fragment實現
2. Fragment能夠被附加到容器中,也能夠被其它Fragment替換,也能夠被從容器中移除,不管是哪一種操做,對於Fragment的宿主Activity及該Activity中其它的部分不會產生影響
3. Fragment有獨立的生命週期
【建立流程】
1. 自定義View,繼承android.support.v4.app.Fragment
2. 重寫onCreateView()方法,肯定須要顯示的內容的View對象,並做爲該方法的返回值
【使用ViewPager+Fragment】
1. 將Activity類修改成繼承自FragmentActivity
2. 自定義類,繼承android.support.v4.app.FragmentPagerAdapter,並重寫抽象方法
3. 在自定義的FragmentPagerAdapter中定義構造方法時,須要FragmentManager對象,能夠經過調用getSupportFragmentManager()方法獲取
4. 在自定義的FragmentPagerAdapter中的getItem()方法中,根據參數position建立不一樣的Fragment對象。
【注意事項】
1. 因爲Fragment不是Context的子孫類,在Fragment中須要Context對象時,應該經過調用getActivity()獲取其宿主Activity的對象,用於表示上下文對象java

public class MainActivity extends FragmentActivity {
    // 按鈕:團購
    private Button btnMenuDeal;
    // 按鈕:附近
    private Button btnMenuNearby;
    // 按鈕:個人
    private Button btnMenuMy;
    // 按鈕:更多
    private Button btnMenuMore;
    // Fragment容器
    private FrameLayout flContainer;
    // Fragment的Adapter
    private FragmentPagerAdapter fragmentAdapter;
    // 上次顯示的Fragment的position,用於顯示新Fragment時,把舊的移除
    private int lastPosition;
    // 上次顯示的Fragment對象,用於顯示新Fragment時,把舊的移除
    private Object lastItem;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        // 初始化底部菜單的4個按鈕
        btnMenuDeal = (Button) findViewById(R.id.btn_menu_deal);
        btnMenuNearby = (Button) findViewById(R.id.btn_menu_nearby);
        btnMenuMy = (Button) findViewById(R.id.btn_menu_my);
        btnMenuMore = (Button) findViewById(R.id.btn_menu_more);
        // 爲底部菜單的4個按鈕配置點擊監聽
        MenuButtonOnClickListener listener = new MenuButtonOnClickListener();
        btnMenuDeal.setOnClickListener(listener);
        btnMenuNearby.setOnClickListener(listener);
        btnMenuMy.setOnClickListener(listener);
        btnMenuMore.setOnClickListener(listener);
        // 初始化Fragment容器:FrameLayout
        flContainer = (FrameLayout) findViewById(R.id.fl_container);
        // 爲Fragment容器配置Adapter(僅當使用ViewPager做爲容器時使用)
        fragmentAdapter = new InnerPagerAdapter();
        // flContainer.setAdapter(adapter);
        
        // 默認選中第1個
        selectMenuItem(btnMenuDeal);
        // 手動執行監聽器,以觸發顯示第1個Fragment
        listener.onClick(btnMenuDeal);
    }
    
    private class InnerPagerAdapter extends FragmentPagerAdapter {

        public InnerPagerAdapter() {
            super(getSupportFragmentManager());
        }

        @Override
        public Fragment getItem(int position) {
            Fragment fragment = null;
            switch (position) {
            case 0:
                fragment = new DealFragment();
                break;
            case 1:
                fragment = new NearByFragment();
                break;
            case 2:
                fragment = new MyFragment();
                break;
            case 3:
                fragment = new MoreFragment();
                break;
            }
            return fragment;
        }

        @Override
        public int getCount() {
            return 4;
        }
        
    }
    
    /**
     * Tab菜單點擊事件監聽器
     */
    private class MenuButtonOnClickListener implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            int position = 0;
            switch (v.getId()) {
            case R.id.btn_menu_deal:
                position = 0;
                selectMenuItem(btnMenuDeal);
                break;
                
            case R.id.btn_menu_nearby:
                position = 1;
                selectMenuItem(btnMenuNearby);
                break;
                
            case R.id.btn_menu_my:
                position = 2;
                selectMenuItem(btnMenuMy);
                break;
                
            case R.id.btn_menu_more:
                position = 3;
                selectMenuItem(btnMenuMore);
                break;
            }
            
            // 若是已經顯示了Fragment,則從容器中移除
            if(lastItem != null) {
                fragmentAdapter.destroyItem(flContainer, lastPosition, lastItem);
            }
            // 肯定當前須要被顯示的Fragment對象
            Object fragment = fragmentAdapter.instantiateItem(flContainer, position);
            // 記錄下當前顯示的Fragment的position
            lastPosition = position;
            // 記錄下當前顯示的Fragment
            lastItem = fragment;
            // 設置當前顯示的Fragment
            fragmentAdapter.setPrimaryItem(flContainer, 0, fragment);
            // 更新顯示
            fragmentAdapter.finishUpdate(flContainer);
        }
        
    }
    
    
    /**
     * 選擇底部菜單中的某一項
     * @param v 被選中的項
     */
    private void selectMenuItem(View v) {
        // 實現基本思路是選中1個,取消選中3個
        // 具體實現時,能夠先取消選中全部,而後選中1個
        // 取消選中全部
        btnMenuDeal.setSelected(false);
        btnMenuNearby.setSelected(false);
        btnMenuMy.setSelected(false);
        btnMenuMore.setSelected(false);
        // 選中參數對應的控件
        v.setSelected(true);
    }

}

另外一種方法實現fragment之間的切換:android

@EActivity(resName="main_fragment")
public class MainFragmentActivity extends FragmentActivity{
    SportFragment sportFragment;
    DiscoverFragment discoverFragment;
    MessageFragment messageFragment;
    MeFragment meFragment;
    
    @ViewsById({R.id.btn_main_fragment_sport,
    R.id.btn_main_fragment_discover,
    R.id.btn_main_fragment_message,
    R.id.btn_main_fragment_me})
    ArrayList<Button> btnList=new ArrayList<Button>();
    
    //放四個fragment
    Fragment[] fragments=new Fragment[4];
    /**
     * 當前顯示的是第幾個fragment
     */
    int currentFragmentIndex=0;
    int clickIndex=0;
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
    int orientation=    newConfig.orientation;
    LogUtil.i("屏幕方向", "activity onConfigurationChanged"+orientation);

        super.onConfigurationChanged(newConfig);
    }
    @Override
    protected void onCreate(Bundle arg0) {
        // TODO Auto-generated method stub
        super.onCreate(arg0);
        try {
            LogUtil.i("屏幕方向", "activity onCreate");
            sportFragment=new SportFragment();
            discoverFragment=new DiscoverFragment();
            messageFragment=new MessageFragment();
            meFragment=new MeFragment();
            
            fragments[0]=sportFragment;
            fragments[1]=discoverFragment;
            fragments[2]=messageFragment;
            fragments[3]=meFragment;
            
            FragmentManager manager=this.getSupportFragmentManager();
            //Transaction事務
            FragmentTransaction transaction=manager.beginTransaction();
            //把sportFragment放到linearLayout
            transaction.add(R.id.fragment_container, sportFragment);
            transaction.show(sportFragment);
            //提交
            transaction.commit();
            
            
        } catch (Exception e) {
            ExceptionUtil.handlerException(e);
        }
    }
    //代碼執行順序 onCreate-->ViewsById-->AfterView
    @AfterViews
    public void addListener()
    {
        //設置當前按鈕的狀態
        btnList.get(currentFragmentIndex).setSelected(true);
        
        MyListener myListener=new MyListener();
        for (Button btn:btnList)
        {
            btn.setOnClickListener(myListener);
        }
    }
    class MyListener implements OnClickListener
    {

        @Override
        public void onClick(View v) {
            
            try {
                switch (v.getId()) {
                case R.id.btn_main_fragment_sport:
                    clickIndex=0;
                    break;
                case R.id.btn_main_fragment_discover:
                    clickIndex=1;
                    break;
                case R.id.btn_main_fragment_message:
                    clickIndex=2;
                    break;
                case R.id.btn_main_fragment_me:
                    clickIndex=3;
                    break;
                }
                if (clickIndex!=currentFragmentIndex)
                {
                    //單擊別的按鈕,顯示另一個fragment
                    Fragment showFragment=fragments[clickIndex];
                    FragmentTransaction transaction=getSupportFragmentManager().beginTransaction();
                    if (!showFragment.isAdded())
                    {
                        //之前沒有顯示過
                        transaction.add(R.id.fragment_container, showFragment);                        
                    }
                    transaction.hide(fragments[currentFragmentIndex]);
                    transaction.show(showFragment);
                    transaction.commit();
                    btnList.get(currentFragmentIndex).setSelected(false);
                    btnList.get(clickIndex).setSelected(true);
                    
                    currentFragmentIndex=clickIndex;
                    
                }
            } catch (Exception e) {
                ExceptionUtil.handlerException(e);
            }
        }
        
    }
}
相關文章
相關標籤/搜索