android項目剖解之ViewPager+Fragment 實現tabhost效果

來源:互聯網
上載者:User

android項目剖解之ViewPager+Fragment 實現tabhost效果

項目中需要用到底欄導覽列,滑動或者點擊會切換上面的視圖,

 

這個效果使用Viewpager+Fragmen實現是主流方案,加入你之前對fragment不太瞭解,可以先看android之Fragment(官網資料翻譯)

整個檔案如下:

好了廢話少說,先上布局檔案:main.xml

 

其實上面的整個布局非常簡單,就是ViewPager+LinearLayout,寫完mian後,後面寫lay1,lay2,lay3等檔案,都只是普通布局檔案,就不貼代碼了,回頭可以下載代碼查看。

 

接下來是 MainActivity.java

 

package com.vatty.activity;import java.util.ArrayList;import java.util.HashMap;import java.util.Map;import android.content.res.Resources;import android.os.Bundle;import android.support.v4.app.Fragment;import android.support.v4.app.FragmentActivity;import android.support.v4.view.ViewPager;import android.support.v4.view.ViewPager.OnPageChangeListener;import android.util.DisplayMetrics;import android.util.Log;import android.view.View;import android.view.Window;import android.view.animation.Animation;import android.view.animation.TranslateAnimation;import android.widget.ImageView;import android.widget.TextView;/** *  * MainActivity.java * @author mayi * 2014-8-2 下午11:51:28 * */public class MainActivity extends FragmentActivity {    private static final String TAG = MainActivity;    private ViewPager mPager;    private ArrayList fragmentsList;    private ImageView ivBottomLine;    private TextView tv_tab_1, tv_tab_2, tv_tab_3, tv_tab_4;    private int currIndex = 0;    private int bottomLineWidth;    private int offset = 0;    private int position_one;    private int position_two;    private int position_three;    private Resources resources;    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        requestWindowFeature(Window.FEATURE_NO_TITLE);                setContentView(R.layout.main);                resources = getResources();               InitWidth();                InitTextView();                InitViewPager();    }        /**     * 擷取底欄中的控制項並添加監聽事件     */    private void InitTextView() {        tv_tab_1 = (TextView) findViewById(R.id.tv_tab_1);        tv_tab_2 = (TextView) findViewById(R.id.tv_tab_2);        tv_tab_3 = (TextView) findViewById(R.id.tv_tab_3);        tv_tab_4 = (TextView) findViewById(R.id.tv_tab_4);        tv_tab_1.setOnClickListener(new MyOnClickListener(0));        tv_tab_2.setOnClickListener(new MyOnClickListener(1));        tv_tab_3.setOnClickListener(new MyOnClickListener(2));        tv_tab_4.setOnClickListener(new MyOnClickListener(3));    }    /**     * 初始化ViewPager     */    private void InitViewPager() {    //擷取布局中的viewpager控制項        mPager = (ViewPager) findViewById(R.id.vPager);        //Fragment容器        fragmentsList = new ArrayList();                 Map paramMap = new HashMap();        paramMap.put(userid,小洪);        paramMap.put(age,23);                        Map paramMap2 = new HashMap();        paramMap2.put(userid,vatty);        paramMap2.put(age,24);                Map paramMap3 = new HashMap();        paramMap3.put(userid,小明);        paramMap3.put(age,25);                        Map paramMap4 = new HashMap();        paramMap4.put(userid,hongshengpeng.com);        paramMap4.put(age,26);               //產生每個tab對應的fragment        Fragment activityfragment = TestFragment.newInstance(Hello Activity.,paramMap);        Fragment groupFragment = TestFragment.newInstance(Hello Group.,paramMap2);        Fragment friendsFragment=TestFragment.newInstance(Hello Friends.,paramMap3);        Fragment chatFragment=TestFragment.newInstance(Hello Chat.,paramMap4);        //添加到Fragment容器中        fragmentsList.add(activityfragment);        fragmentsList.add(groupFragment);        fragmentsList.add(friendsFragment);        fragmentsList.add(chatFragment);        //給ViewPager添加適配器        mPager.setAdapter(new MyFragmentPagerAdapter(getSupportFragmentManager(), fragmentsList));        //設定預設的視圖為第0個        mPager.setCurrentItem(0);        //給Viewpager添加監聽事件        mPager.setOnPageChangeListener(new MyOnPageChangeListener());    }        /**     *  初始化底欄,擷取相應寬度資訊     */    private void InitWidth() {        ivBottomLine = (ImageView) findViewById(R.id.iv_bottom_line);        //擷取底欄白色滑動線的寬度        bottomLineWidth = ivBottomLine.getLayoutParams().width;        Log.d(TAG, cursor imageview width= + bottomLineWidth);                //擷取螢幕寬度        DisplayMetrics dm = new DisplayMetrics();        getWindowManager().getDefaultDisplay().getMetrics(dm);        int screenW = dm.widthPixels;        //螢幕分4份,計算出每份中白色滑條外的間隔距離        offset = (int) ((screenW / 4.0 - bottomLineWidth) / 2);        Log.i(MainActivity, offset= + offset);                //計算出底欄的位置        position_one = (int) (screenW / 4.0);        position_two = position_one * 2;        position_three = position_one * 3;    }            /**     * 自訂監聽類   如此定義監聽類,可以實現共用。     * @author Administrator     *     */    public class MyOnClickListener implements View.OnClickListener {        private int index = 0;        public MyOnClickListener(int i) {            index = i;        }        @Override        public void onClick(View v) {        //設定ViewPager的當前view            mPager.setCurrentItem(index);        }    };        /**     * 頁面滑動監聽     * @author Administrator     *     */    public class MyOnPageChangeListener implements OnPageChangeListener {        @Override        public void onPageSelected(int index) {        //動畫            Animation animation = null;            switch (index) {            case 0:                if (currIndex == 1) {                //代碼產生滑動動畫                animation = new TranslateAnimation(position_one, 0, 0, 0);                //改變tv_tab_2的顏色值,使其沒有選中的效果                    tv_tab_2.setTextColor(resources.getColor(R.color.lightwhite));                } else if (currIndex == 2) {                    animation = new TranslateAnimation(position_two, 0, 0, 0);                    tv_tab_3.setTextColor(resources.getColor(R.color.lightwhite));                } else if (currIndex == 3) {                    animation = new TranslateAnimation(position_three, 0, 0, 0);                    tv_tab_4.setTextColor(resources.getColor(R.color.lightwhite));                }                //改變tv_tab_1的顏色值,使其有選中的效果                tv_tab_1.setTextColor(resources.getColor(R.color.white));                break;            case 1:                if (currIndex == 0) {                    animation = new TranslateAnimation(0, position_one, 0, 0);                    tv_tab_1.setTextColor(resources.getColor(R.color.lightwhite));                } else if (currIndex == 2) {                    animation = new TranslateAnimation(position_two, position_one, 0, 0);                    tv_tab_3.setTextColor(resources.getColor(R.color.lightwhite));                } else if (currIndex == 3) {                    animation = new TranslateAnimation(position_three, position_one, 0, 0);                    tv_tab_4.setTextColor(resources.getColor(R.color.lightwhite));                }                tv_tab_2.setTextColor(resources.getColor(R.color.white));                break;            case 2:                if (currIndex == 0) {                    animation = new TranslateAnimation(0, position_two, 0, 0);                    tv_tab_1.setTextColor(resources.getColor(R.color.lightwhite));                } else if (currIndex == 1) {                    animation = new TranslateAnimation(position_one, position_two, 0, 0);                    tv_tab_2.setTextColor(resources.getColor(R.color.lightwhite));                } else if (currIndex == 3) {                    animation = new TranslateAnimation(position_three, position_two, 0, 0);                    tv_tab_4.setTextColor(resources.getColor(R.color.lightwhite));                }                tv_tab_3.setTextColor(resources.getColor(R.color.white));                break;            case 3:                if (currIndex == 0) {                    animation = new TranslateAnimation(0, position_three, 0, 0);                    tv_tab_1.setTextColor(resources.getColor(R.color.lightwhite));                } else if (currIndex == 1) {                    animation = new TranslateAnimation(position_one, position_three, 0, 0);                    tv_tab_2.setTextColor(resources.getColor(R.color.lightwhite));                } else if (currIndex == 2) {                    animation = new TranslateAnimation(position_two, position_three, 0, 0);                    tv_tab_3.setTextColor(resources.getColor(R.color.lightwhite));                }                tv_tab_4.setTextColor(resources.getColor(R.color.white));                break;            }            //記錄當前的頁面位置            currIndex = index;            //動畫播放完後,保持結束時的狀態            animation.setFillAfter(true);            //動畫期間            animation.setDuration(300);            //底欄滑動白線開始動畫            ivBottomLine.startAnimation(animation);        }        @Override        public void onPageScrolled(int arg0, float arg1, int arg2) {                }        @Override        public void onPageScrollStateChanged(int arg0) {                }    }}

整個代碼中就是做初始化準備作用,載入layout,拿到各個控制項,設定adapter,添加監聽等。代碼中有比較詳細的注釋,這裡不再講。

 

接下來就是Fragment模組:

TestFragment.java

 

package com.vatty.activity;import java.util.ArrayList;import java.util.Map;import android.os.Bundle;import android.support.v4.app.Fragment;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ListView;import com.vatty.adapter.ContactAdapter;import com.vatty.model.Contact;/** *  * TestFragment.java * @author mayi * 2014-8-2 下午11:54:19 * */public class TestFragment extends Fragment {private static final String TAG = TestFragment;private Map maplist;/** * 擷取新的Fragment * @param s * @param map * @return */static TestFragment newInstance(String s, Map map) {TestFragment newFragment = new TestFragment();final SerializableMap myMap = new SerializableMap();myMap.setMap(map);//Bundle 儲存資料Bundle bundle = new Bundle();bundle.putSerializable(map, myMap);//Fragment傳送資料newFragment.setArguments(bundle);return newFragment;}@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);//Log.d(TAG, TestFragment-----onCreate);//擷取Fragment傳送的資料Bundle bundle = getArguments();SerializableMap serializableMap = (SerializableMap) bundle.get(map);maplist = serializableMap.getMap();}@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {//Log.d(TAG, TestFragment-----onCreateView);//載入要在此Fragment中顯示的layout(布局檔案)View view = inflater.inflate(R.layout.lay1, container, false);//-------------------------------以下的根據自己項目的需要做開發----------------------------------------------//擷取layout中的控制項ListView lv = (ListView) view.findViewById(R.id.listView3);//getActivity().getApplicationContext()方法  擷取ContextContactAdapter hc = new ContactAdapter(getActivity().getApplicationContext(), getContact());lv.setAdapter(hc);lv.setCacheColorHint(0);return view;}private ArrayList getContact() {ArrayList hcList = new ArrayList();for (int i = 0; i < 10; i++) {Contact c0 = new Contact();c0.setTxPath(R.drawable.more_game + );c0.setName(maplist.get(userid) +   年齡: + maplist.get(age));hcList.add(c0);}return hcList;}@Overridepublic void onDestroy() {super.onDestroy();//Log.d(TAG, TestFragment-----onDestroy);}}

至此,整個demo中主要的代碼模組已經展現了,其他類似adapter的,就跟我們平常開發的沒多大區別,大家可以去下載代碼查看。

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.