使用ViewPager+Fragment實現(xiàn)選項卡切換效果

實現(xiàn)效果

本實例主要實現(xiàn)用ViewPage和Fragment實現(xiàn)選項卡切換效果,選項卡個數(shù)為3個,點(diǎn)擊選項卡或滑動屏幕會切換Fragment并實現(xiàn)選項卡下方下邊框條跟隨移動效果。

本程序用android4.2.2真機(jī)調(diào)試,為方便部署,我使用adbWireless做為部署工具,電腦和手機(jī)接入同一局域網(wǎng),在PC端輸入名稱adb connect 手機(jī)端ip 默認(rèn)連接5555端口。之后再Eclipse的Devices中即可看到介入設(shè)備。前提是android系統(tǒng)需要Root。如下圖:

2015-06-21_090912.png

設(shè)計實現(xiàn)

  • 創(chuàng)建項目(此過程不做贅述)
  • 在activity_main.xml中設(shè)置布局。xml內(nèi)容如下:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.fengzhengapp.MainActivity" >
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="48dp"
        android:orientation="horizontal" >
        <TextView
            android:id="@+id/tv_hot"
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:layout_weight="1.0"
            android:background="#ffEAEAEA"
            android:gravity="center"
            android:text="@string/tab_hot"
            android:textSize="18sp" />
        <TextView
            android:id="@+id/tv_news"
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:layout_weight="1.0"
            android:background="#ffEAEAEA"
            android:gravity="center"
            android:text="@string/tab_news"
            android:textSize="18sp" />
        <TextView
            android:id="@+id/tv_fav"
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:layout_weight="1.0"
            android:background="#ffEAEAEA"
            android:gravity="center"
            android:text="@string/tab_favorite"
            android:textSize="18sp" />
    </LinearLayout>
    <ImageView
        android:id="@+id/cursor"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:scaleType="matrix"
        android:src="@drawable/bgborder" />
    <android.support.v4.view.ViewPager
        android:id="@+id/myViewPager"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:flipInterval="30" >
    </android.support.v4.view.ViewPager>
</LinearLayout>

上面布局頁實現(xiàn)的效果如下:

2015-06-21_112628.png
  • 接下來,增加3個Fragment布局頁 ,分別在里面填充簡單的內(nèi)容
    第一個
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <TextView
        android:id="@+id/txtHot"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:text="this is the hot tab" >
    </TextView>
</LinearLayout>

第二個

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <TextView
        android:id="@+id/txtNews"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:text="this is the news tab" >
    </TextView>
</LinearLayout>

第三個:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <TextView
        android:id="@+id/txtFav"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:text="this is the Fav tab" >
    </TextView>
</LinearLayout>

以上3個Fragment的布局文件已創(chuàng)建完畢,每個文件中只顯示簡單的文本內(nèi)容,用做演示。

  • 加載3個Fragment到Activity中。

首先實現(xiàn)3個Fragment對應(yīng)的后臺類

熱點(diǎn)布局頁對應(yīng)的類:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FragmentHot extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragmenthot, container, false);
        return view;
    }
}
news布局頁對應(yīng)的類:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FragmentNews extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragmentnews, container, false);
        return view;
    }
}
收藏布局頁對應(yīng)的類:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FragmentFavorite extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragmentfav, container, false);
        return view;
    }
}
  • 之后再activity中初始化這3個Fragment

注意要點(diǎn):
Activity繼承自FragmentActivity
要實現(xiàn)一個FragmentPagerAdapter,內(nèi)容如下:

import java.util.ArrayList;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class MyFragmentAdapter extends FragmentPagerAdapter {
    ArrayList<Fragment> list;
    public MyFragmentAdapter(FragmentManager fm,ArrayList<Fragment> list){
        super(fm);
        this.list = list;
    }
    @Override
    public Fragment getItem(int arg0) {
        // TODO Auto-generated method stub
        return list.get(arg0);
    }
    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return list.size();
    }
}

然后在Activity中實現(xiàn)切換和動畫效果,代碼如下:

import java.util.ArrayList;
import android.app.Activity;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.support.v4.app.FragmentActivity;
import android.view.MenuItem;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends FragmentActivity {
    private ViewPager mViewPager;
    private ArrayList fragments;
    private TextView view1, view2, view3;  
    private int currIndex;
    private ImageView image;
    private static int bmpW;//橫線圖片寬度  
    private static int offset;//圖片移動的偏移量  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initViewPager();
        InitTextView();
        InitImage();
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
    private void InitTextView(){
        view1 = (TextView) findViewById(R.id.tv_hot);
        view2 = (TextView) findViewById(R.id.tv_news);
        view3 = (TextView) findViewById(R.id.tv_fav);
        view1.setOnClickListener(new txtListener(0));
        view2.setOnClickListener(new txtListener(1));
        view3.setOnClickListener(new txtListener(2));
    }
    //內(nèi)部類 重寫TextView點(diǎn)擊事件
    public class txtListener implements View.OnClickListener{
        private int index = 0;
        public txtListener(int i){
            index = i;
        }
        @Override
        public void onClick(View v){
            mViewPager.setCurrentItem(index);
        }
    }
    /* 
     * 初始化圖片的位移像素 
     */  
    public void InitImage(){  
        image = (ImageView)findViewById(R.id.cursor);  
        bmpW = BitmapFactory.decodeResource(getResources(), R.drawable.bgborder).getWidth();  
        DisplayMetrics dm = new DisplayMetrics();  
        getWindowManager().getDefaultDisplay().getMetrics(dm);  
        int screenW = dm.widthPixels;  
        offset = (screenW/3 - bmpW)/2;  
        Log.i("screenW",String.valueOf(screenW));
        Log.i("bmpW",String.valueOf(bmpW));
        Log.i("offset",String.valueOf(offset));
        //imgageview設(shè)置平移,使下劃線平移到初始位置(平移一個offset)  
        Matrix matrix = new Matrix();  
        matrix.postTranslate(offset, 0);  
        image.setImageMatrix(matrix);  
    }  
    private void initViewPager(){
        mViewPager = (ViewPager)findViewById(R.id.myViewPager);
        fragments = new ArrayList<Fragment>();
        Fragment fragmentHot = new FragmentHot();
        Fragment fragmentNews = new FragmentNews();
        Fragment fragmentFav = new FragmentFavorite();
        fragments.add(fragmentHot);
        fragments.add(fragmentNews);
        fragments.add(fragmentFav);
        mViewPager.setAdapter(new MyFragmentAdapter(getSupportFragmentManager(), fragments));
        mViewPager.setCurrentItem(0);
        mViewPager.setOnPageChangeListener(new myOnPageChangeListener());
    }
    public class myOnPageChangeListener implements OnPageChangeListener {
        private int one = offset*2 +bmpW;//兩個相鄰頁面的偏移量   
        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }
        @Override
        public void onPageScrollStateChanged(int arg0) {
            // TODO Auto-generated method stub
        }
        @Override  
        public void onPageSelected(int arg0) {  
            // TODO Auto-generated method stub  
            Log.i("aaaaaaaaaaaaa",String.valueOf(arg0));
            Log.i("one",String.valueOf(one));
            Animation animation = new TranslateAnimation(currIndex*one,arg0*one,0,0);//平移動畫  
            currIndex = arg0; 
            animation.setFillAfter(true);//動畫終止時停留在最后一幀,不然會回到?jīng)]有執(zhí)行前的狀態(tài)  
            animation.setDuration(200);//動畫持續(xù)時間0.2秒  
            image.startAnimation(animation);//是用ImageView來顯示動畫的  
            //int i = currIndex + 1;  
           // Toast.makeText(MainActivity.this, "您選擇了第"+i+"個頁卡", Toast.LENGTH_SHORT).show();  
        }  
    }  
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容