//布局
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout 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="com.bwei.www.fragment1022.MainActivity"> <android.support.v4.view.ViewPager android:id="@+id/vp_banner" android:layout_width="match_parent" android:layout_height="match_parent"> </android.support.v4.view.ViewPager> <LinearLayout android:layout_alignParentBottom="true" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content"> <TextView android:id="@+id/message" android:text="消息" android:gravity="center" android:layout_weight="1" android:textSize="22sp" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:id="@+id/mine" android:text="我的" android:textSize="22sp" android:gravity="center" android:layout_weight="1" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout> </RelativeLayout>
//主页面
package com.bwei.www.fragment1022; import android.graphics.Color; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.TextView; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity implements View.OnClickListener { private ViewPager vpBanner; private TextView txtMessage; private TextView txtMine; private List<Fragment> fragmentList; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); vpBanner = findViewById(R.id.vp_banner); txtMessage = findViewById(R.id.message); txtMine = findViewById(R.id.mine); fragmentList = new ArrayList<>(); MessageFragment messageFragment = new MessageFragment(); MineFragment mineFragment = new MineFragment(); fragmentList.add(messageFragment); fragmentList.add(mineFragment); txtMessage.setOnClickListener(this); txtMine.setOnClickListener(this); vpBanner.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) { @Override public Fragment getItem(int position) { return fragmentList.get(position); } @Override public int getCount() { return fragmentList.size(); } }); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.message: vpBanner.setCurrentItem(0); //只是点击能变颜色 滑动不会跟着变 txtMessage.setBackgroundColor(Color.GREEN); txtMine.setBackgroundColor(Color.WHITE); break; case R.id.mine: vpBanner.setCurrentItem(1); //只是点击能变颜色 滑动不会跟着变 txtMessage.setBackgroundColor(Color.WHITE); txtMine.setBackgroundColor(Color.GREEN); break; } } }