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.Button; import java.util.ArrayList; public class MainActivity extends AppCompatActivity implements View.OnClickListener{ private Button toutiao; private Button guonei; private Button junshi; private Button keji; private int count = 0; private ViewPager viewpager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); init(); final ArrayList<Fragment> fs = new ArrayList<>(); Fragment1 fragment1 = new Fragment1(); Fragment2 fragment2 = new Fragment2(); Fragment3 fragment3 = new Fragment3(); Fragment4 fragment4 = new Fragment4(); fs.add(fragment1); fs.add(fragment2); fs.add(fragment3); fs.add(fragment4); viewpager = (ViewPager) findViewById(R.id.viewpager); viewpager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) { @Override public Fragment getItem(int position) { return fs.get(position); } @Override public int getCount() { return fs.size(); } }); viewpager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { demo(position); } @Override public void onPageScrollStateChanged(int state) { } }); } private void init() { toutiao = (Button) findViewById(R.id.toutiao); guonei = (Button) findViewById(R.id.guonei); junshi = (Button) findViewById(R.id.junshi); keji = (Button) findViewById(R.id.keji); toutiao.setOnClickListener(this); guonei.setOnClickListener(this); junshi.setOnClickListener(this); keji.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.toutiao: count = 0; break; case R.id.guonei: count = 1; break; case R.id.junshi: count = 2; break; case R.id.keji: count = 3; break; } viewpager.setCurrentItem(count); demo(count); } public void demo(int count){ toutiao.setTextColor(count == 0? Color.RED:Color.BLACK); guonei.setTextColor(count == 1? Color.RED:Color.BLACK); junshi.setTextColor(count == 2? Color.RED:Color.BLACK); keji.setTextColor(count == 3? Color.RED:Color.BLACK); } }
Fragment
最新推荐文章于 2022-10-15 20:35:19 发布