fragment与viewpager结合 一个简单的WeChat首页

发布时间 2023-04-14 00:11:28作者: 林浅

BlankFragment

package com.example.wechatpage;

import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link BlankFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class BlankFragment extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_TEXT = "param1";

    // TODO: Rename and change types of parameters
    private String mTextString;
    View rootView;

    public BlankFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @return A new instance of fragment BlankFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static BlankFragment newInstance(String param1) {
        BlankFragment fragment = new BlankFragment();
        Bundle args = new Bundle();
        args.putString(ARG_TEXT, param1);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mTextString = getArguments().getString(ARG_TEXT);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        if(rootView==null){
            rootView =  inflater.inflate(R.layout.fragment_blank, container, false);
        }
        initView();
        return rootView;
    }

    private void initView() {
        TextView textView = rootView.findViewById(R.id.text);
        textView.setText(mTextString);
    }
}

MainActivity

package com.example.wechatpage;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.widget.ViewPager2;

import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private LinearLayout llchat,llfaxian,lltongxunlu,llwode;
    private ImageView ivchat,ivfaxian,ivtongxunlu,ivwode,ivCurrent;

    ViewPager2 viewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initPager();
        initTabView();
    }

    private void initTabView() {
        llchat = findViewById(R.id.id_tab_weixin);
        llchat.setOnClickListener(this);
        llfaxian = findViewById(R.id.id_tab_faxian);
        llfaxian.setOnClickListener(this);
        lltongxunlu = findViewById(R.id.id_tab_tongxunlu);
        lltongxunlu.setOnClickListener(this);
        llwode = findViewById(R.id.id_tab_wode);
        llwode.setOnClickListener(this);
        ivchat =findViewById(R.id.tab_iv_weixin);
        ivtongxunlu =findViewById(R.id.tab_iv_tongxunlu);
        ivfaxian =findViewById(R.id.tab_iv_faxian);
        ivwode =findViewById(R.id.tab_iv_wode);

        ivchat.setSelected(true);
        ivCurrent=ivchat;
    }

    private void initPager() {
        viewPager =findViewById(R.id.viewPage);
        ArrayList<Fragment> fragments = new ArrayList<>();
        fragments.add(BlankFragment.newInstance("微信聊天"));
        fragments.add(BlankFragment.newInstance("通讯录"));
        fragments.add(BlankFragment.newInstance("发现"));
        fragments.add(BlankFragment.newInstance("我"));
        MyFragmentPagerAdapter myFragmentPagerAdapter = new MyFragmentPagerAdapter(getSupportFragmentManager(),getLifecycle(),fragments);
        viewPager.setAdapter(myFragmentPagerAdapter);
        viewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                changeTab(position);
            }


            @Override
            public void onPageScrollStateChanged(int state) {
                super.onPageScrollStateChanged(state);
            }

            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                super.onPageScrolled(position, positionOffset, positionOffsetPixels);
            }
        });


    }

    private void changeTab(int position) {
        ivCurrent.setSelected(false);
        switch (position){
            case R.id.id_tab_weixin:
                viewPager.setCurrentItem(0);
            case 0:
                ivchat.setSelected(true);
                ivCurrent = ivchat;
                break;
            case R.id.id_tab_tongxunlu:
                viewPager.setCurrentItem(1);
            case 1:
                ivtongxunlu.setSelected(true);
                ivCurrent = ivtongxunlu;
                break;
            case R.id.id_tab_faxian:
                viewPager.setCurrentItem(2);
            case 2:
                ivfaxian.setSelected(true);
                ivCurrent = ivfaxian;
                break;
            case R.id.id_tab_wode:
                viewPager.setCurrentItem(3);
            case 3:
                ivwode.setSelected(true);
                ivCurrent =ivwode;
                break;
        }
    }

    @Override
    public void onClick(View view) {
        changeTab(view.getId());

    }
}

MyFragmentPagerAdapter

package com.example.wechatpage;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.lifecycle.Lifecycle;
import androidx.viewpager2.adapter.FragmentStateAdapter;

import java.util.ArrayList;
import java.util.List;

public class MyFragmentPagerAdapter extends FragmentStateAdapter {
    List<Fragment> fragmentList =new ArrayList<>();
    public MyFragmentPagerAdapter(@NonNull FragmentManager fragmentManager, @NonNull Lifecycle lifecycle,List<Fragment> fragments) {
        super(fragmentManager, lifecycle);
        fragmentList = fragments;
    }

    @NonNull
    @Override
    public Fragment createFragment(int position) {
        return fragmentList.get(position);
    }

    @Override
    public int getItemCount() {
        return fragmentList.size();
    }
}

组件:

tab_faxian.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/faxian_pressed" android:state_selected="true" />
    <item android:drawable="@drawable/faxian_normal"></item>
</selector>

tab_tongxunlu.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/tongxunlu_pressed" android:state_selected="true" />
    <item android:drawable="@drawable/tongxunlu_normal"></item>
</selector>

tab_weixin.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/weixin_pressed" android:state_selected="true" />
    <item android:drawable="@drawable/weixin_normal"></item>
</selector>

 

tab_wode.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/wode_pressed" android:state_selected="true" />
    <item android:drawable="@drawable/wode_normal"></item>
</selector>

布局文件

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    tools:context=".MainActivity"
    android:orientation="vertical">

    <androidx.viewpager2.widget.ViewPager2
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:id="@+id/viewPage"
        />
    <include layout="@layout/buttom_layout"></include>


</LinearLayout>

buttom_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="55dp"
    android:background="#e0e0e0"
    >

    <LinearLayout
        android:id="@+id/id_tab_weixin"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:orientation="vertical"
        tools:ignore="Suspicious0dp" >
        <ImageView
            android:layout_width="32dp"
            android:layout_height="32dp"
            android:id="@+id/tab_iv_weixin"
            android:background="@drawable/tab_weixin">

        </ImageView>
        <TextView
            android:layout_width="32dp"
            android:layout_height="wrap_content"
            android:id="@+id/text_weixin"
            android:gravity="center"
            android:text="微信"
            />


    </LinearLayout>


    <LinearLayout
        android:id="@+id/id_tab_tongxunlu"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:orientation="vertical"
        tools:ignore="Suspicious0dp" >
        <ImageView
            android:layout_width="32dp"
            android:layout_height="32dp"
            android:id="@+id/tab_iv_tongxunlu"
            android:background="@drawable/tab_tongxunlu">

        </ImageView>
        <TextView
            android:layout_width="32dp"
            android:layout_height="wrap_content"
            android:id="@+id/text_tongxunlu"
            android:gravity="center"
            android:text="通讯录"
            />


    </LinearLayout>
    <LinearLayout
        android:id="@+id/id_tab_faxian"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:orientation="vertical"
        tools:ignore="Suspicious0dp" >
        <ImageView
            android:layout_width="32dp"
            android:layout_height="32dp"
            android:id="@+id/tab_iv_faxian"
            android:background="@drawable/tab_faxian">

        </ImageView>
        <TextView
            android:layout_width="32dp"
            android:layout_height="wrap_content"
            android:id="@+id/text_faxian"
            android:gravity="center"
            android:text="发现"
            />


    </LinearLayout>
    <LinearLayout
        android:id="@+id/id_tab_wode"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:orientation="vertical"
        tools:ignore="Suspicious0dp" >
        <ImageView
            android:layout_width="32dp"
            android:layout_height="32dp"
            android:id="@+id/tab_iv_wode"
            android:background="@drawable/tab_wode">

        </ImageView>
        <TextView
            android:layout_width="32dp"
            android:layout_height="wrap_content"
            android:id="@+id/text_wode"
            android:gravity="center"
            android:text="我的"
            />


    </LinearLayout>



</LinearLayout>

fragment_blank.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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"
    tools:context=".BlankFragment">

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="@string/hello_blank_fragment"
        android:id="@+id/text"
        android:textSize="36dp"
        />

</FrameLayout>