教你使用Fragment + ViewPager制作一款底部滑動(dòng)APP

滑動(dòng)切換頁面是一個(gè)很普遍基礎(chǔ)的技術(shù),很多APP的開發(fā)都會(huì)涉及到這部分。今天就由我來帶領(lǐng)你們“吃通”這個(gè)技術(shù)。

先展示一下效果:

483488.gif

項(xiàng)目源代碼的地址:
https://github.com/WeCheir/Fragment-ViewPager

首先,創(chuàng)建一個(gè)空的MainActivity

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

修改activity_main中的布局,添加三個(gè)RadioButton和一個(gè)ViewPager。
為了減少代碼代碼量,先在style.xml中添加下面幾段代碼:

<style name="radioBtn">
        <item name="android:button">@null</item>
        <item name="android:padding">15dp</item>
        <item name="android:gravity">center</item>
    </style>

在每一個(gè)RadioButton中都調(diào)用這個(gè)style

style="@style/radioBtn"
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">

    <RadioGroup
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintBottom_toBottomOf="parent"
            android:orientation="horizontal"
            android:background="#EDEDED"
            android:id="@+id/radioGroup">

        <RadioButton
                android:text="首頁"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/home"
                android:layout_weight="1"
                style="@style/radioBtn"
                android:padding="15dp"
                android:checked="true" />
        <RadioButton
                android:text="新聞"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/news"
                android:layout_weight="1"
                style="@style/radioBtn"/>
        <RadioButton
                android:text="消息"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/info"
                android:layout_weight="1"
                style="@style/radioBtn"/>

    </RadioGroup>

    <android.support.v4.view.ViewPager
            android:id="@+id/viewPager"
            android:layout_width="0dp"
            android:layout_height="0dp"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintBottom_toTopOf="@+id/radioGroup"/>
</android.support.constraint.ConstraintLayout>

PS:有關(guān)ConstraintLayout的用法我就不再這里講解了,如果有需要的話我后面會(huì)再出一篇關(guān)于這方面的博客。
這段代碼貼上去后應(yīng)該是醬紫的:


48615.png

看上去是不是有種空落落的感覺?我們來美化一下RadioButton的樣子吧。
在drawable文件夾中創(chuàng)建一個(gè)名叫draw_bg的Drawable Resuurce File來讓按鈕選中時(shí)背景變色。
使用下面的這段代碼放進(jìn)去:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item   android:state_checked="true">
        <color android:color="#138DF1"/>
    </item>
    <item>
        <color android:color="#EDEDED"/>
    </item>
</selector>

看不懂的話聽我給你解釋一下。
這個(gè)selector是android自定義控件屬性用的東西,用于展示控件不同狀態(tài)時(shí)的樣子。selector中的基本結(jié)構(gòu)為:

<selector>
  <item 狀態(tài)1 color或drawable>
  <item 狀態(tài)2 color或drawable>
  <item  color或drawable>
<selector/>

在selector的每個(gè)節(jié)點(diǎn)中,都可以指定一種狀態(tài),常見的狀態(tài)屬性名稱有:

android:state_pressed:按下
android:state_focused:獲得焦點(diǎn)
android:state_selected:選中
android:state_checkable:可勾選
android:state_checked:勾選
android:state_enable:可用

在selector中的誒個(gè)<item>下還可以添加<shape>、<color>、<bitmap>等節(jié)點(diǎn)設(shè)置更多的顯示效果。
聽完后有點(diǎn)感覺沒?沒有話就忽略了吧(嘿嘿)。
再來創(chuàng)建一個(gè)draw_text來變一下它的文字顏色吧:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true" android:color="#FFF"/>
    <item android:color="#000"/>
</selector>

再RadioButton中調(diào)用一下看看效果:

android:background="@drawable/draw_bg"
android:textColor="@drawable/draw_text"
866663.png

完成上面的任務(wù)后,來添加一下需要切換的頁面:
創(chuàng)建三個(gè)Fragment(Home、Message、News):

public class Home extends Fragment {
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return (View) inflater.inflate(R.layout.home,null);
    }    
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }
}
public class Message extends Fragment {
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return (View) inflater.inflate(R.layout.message,null);
    }
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }
}
public class News extends Fragment {
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return (View) inflater.inflate(R.layout.news,null);
    }
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }
}

布局的話你們隨意,如果怕麻煩的話就直接粘貼下面的吧:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:app="http://schemas.android.com/apk/res-auto"
     xmlns:tools="http://schemas.android.com/tools"
     android:layout_width="match_parent"
     android:layout_height="match_parent" android:background="#099EE2">

    <TextView
        android:text="首頁"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/textView" android:layout_marginTop="8dp"
        app:layout_constraintTop_toTopOf="parent" app:layout_constraintStart_toStartOf="parent"
        android:layout_marginStart="8dp" app:layout_constraintEnd_toEndOf="parent" android:layout_marginEnd="8dp"
        android:layout_marginBottom="8dp" app:layout_constraintBottom_toBottomOf="parent" android:textSize="30sp"
        android:textColor="#FFF"/>
</android.support.constraint.ConstraintLayout>

現(xiàn)在是時(shí)候來拿MainActivity開刀了,把剛剛創(chuàng)建的Fragment與ViewPager關(guān)聯(lián)起來:

public class MainActivity extends AppCompatActivity {
    private ViewPager viewPager;
    private RadioGroup radioGroup;
    private List<Fragment> fragmentList;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
        //裝載Fragment的容器
        fragmentList = new ArrayList<Fragment>();
        fragmentList.add(new Home());
        fragmentList.add(new News());
        fragmentList.add(new Message());
        //利用FragmentStatePagerAdapter來對(duì)數(shù)據(jù)進(jìn)行適配
        FragmentStatePagerAdapter adapter = new FragmentStatePagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int i) {
                return fragmentList.get(i);
            }

            @Override
            public int getCount() {
                return fragmentList.size();
            }
        };
        //給ViewPager指定適配器
        viewPager.setAdapter(adapter);
    }
    private void init() {
        viewPager = findViewById(R.id.viewPager);
        radioGroup = findViewById(R.id.radioGroup);
    }
}

如果你把上面的代碼運(yùn)行了一遍,你就會(huì)驚喜的發(fā)現(xiàn)——誒,怎么我的按鈕不起作用呢?
這是因?yàn)槲覀冞€沒有給按鈕設(shè)置監(jiān)聽事件,它并不會(huì)這么聰明的知道你按下了它,它就應(yīng)該踢掉一頁Fragment,叫下一個(gè)來頂替。
這里呢,也很簡(jiǎn)單就能實(shí)現(xiàn),添加下面段代碼就行了:

radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch(checkedId){
                    case R.id.home:
                        viewPager.setCurrentItem(0);
                        break;
                    case R.id.news:
                        viewPager.setCurrentItem(1);
                        break;
                    case R.id.info:
                        viewPager.setCurrentItem(2);
                        break;
                    default:
                        break;
                }
            }
        });

這個(gè)setCurrentItem()就是讓ViewPager切換到指定頁面。

//ViewPager滑動(dòng)時(shí)會(huì)自動(dòng)讓RadioButton選中
 viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            //viewPager滑動(dòng)時(shí)會(huì)觸發(fā)
            @Override
            public void onPageScrolled(int i, float v, int i1) {

            }
            //viewPager選中時(shí)會(huì)觸發(fā)
            @Override
            public void onPageSelected(int i) {
                switch(i){
                    case 0:
                        radioGroup.check(R.id.home);
                        break;
                    case 1:
                        radioGroup.check(R.id.news);
                        break;
                    case 2:
                        radioGroup.check(R.id.info);
                        break;
                    default:
                        break;
                }
            }
            //viewPager狀態(tài)改變時(shí)會(huì)觸發(fā)
            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });

好的,終于完工了,午飯加個(gè)雞腿犒勞一下自己。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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