public class MainActivity extends AppCompatActivity implements View.OnClickListener { private ViewPager viewPager1; private Button btnweather,btnlvshi; ArrayList<Button> viewlist = new ArrayList<Button>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.item); initView(); viewPager1.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) { @Override public int getCount() { return 2; } @Override public Fragment getItem(int position) { Fragment fragment = null; switch (position){ case 0: fragment = new WeatherFragment(); break; case 1: fragment = new LvshiFragment(); break; } return fragment; } }); viewPager1.setOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { for(int i = 0;i<viewlist.size();i ++){ Button button = viewlist.get(i); if (i==position) { button.setTextColor(Color.RED); }else { button.setTextColor(Color.BLACK); } } } @Override public void onPageScrollStateChanged(int state) { } }); } private void initView(){ viewPager1 = (ViewPager) findViewById(R.id.mypagerall); btnweather = (Button) findViewById(R.id.weather); btnlvshi = (Button) findViewById(R.id.lvshi); viewlist.add(btnweather); viewlist.add(btnlvshi); for (int i = 0;i<viewlist.size();i++){ viewlist.get(i).setOnClickListener(this); } } @Override public void onClick(View view) { switch (view.getId()){ case R.id.weather: viewPager1.setCurrentItem(0); break; case R.id.lvshi: viewPager1.setCurrentItem(1); break; } } }