Fragment(碎片)

梦想与她 提交于 2019-12-06 16:56:11

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的对象,用于表示上下文对象

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之间的切换:

@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);
            }
        }
        
    }
}


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!