viewpager+fragment切換頁面
阿新 • • 發佈:2018-11-23
佈局中上面一個viewpager控制元件,下面兩個textview或者button控制元件作用於切換頁面按鈕
<?xml version="1.0" encoding="utf-8"?><android.support.v4.view.ViewPager android:id="@+id/vp" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="9"> </android.support.v4.view.ViewPager> <LinearLayout android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:orientation="horizontal"> <TextView android:id="@+id/txt_fl" android:layout_width="0dp" android:layout_weight="1" android:layout_height="wrap_content" android:gravity="center" android:padding="10dp" android:text="分類"/> <TextView android:id="@+id/txt_gwc" android:layout_width="0dp" android:layout_weight="1" android:layout_height="wrap_content" android:gravity="center" android:padding="10dp" android:text="分類"/> </LinearLayout>
MainActvity中
public class MainActivity extends FragmentActivity implements View.OnClickListener{
private ViewPager vp; private TextView txt_fl; private TextView txt_gwc; private List<Fragment> fragments; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //初始化控制元件 initView(); //初始化資料 initData(); } private void initData() {//新增兩個fragment進集合中 fragments = new ArrayList<>(); fragments.add(new FlFragment()); fragments.add(new GwcFragment()); vp.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {//介面卡滑動 @Override public Fragment getItem(int position) { return fragments.get(position); } @Override public int getCount() { return fragments.size(); } }); vp.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {//滑動監聽 @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { ChangbackGround(position); } @Override public void onPageScrollStateChanged(int state) { } }); } private void initView() { vp = (ViewPager) findViewById(R.id.vp); txt_fl = (TextView) findViewById(R.id.txt_fl); txt_gwc = (TextView) findViewById(R.id.txt_gwc); txt_fl.setOnClickListener(this); txt_gwc.setOnClickListener(this); txt_fl.setBackgroundColor(Color.GREEN); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.txt_fl: vp.setCurrentItem(0);//點選到對應的頁面 ChangbackGround(0);//按鈕的背景顏色 break; case R.id.txt_gwc: vp.setCurrentItem(1); ChangbackGround(1); break; } } public void ChangbackGround(int index){//設定按鈕的背景顏色 txt_fl.setBackgroundColor(index==0? Color.GREEN:Color.WHITE); txt_gwc.setBackgroundColor(index==1? Color.GREEN:Color.WHITE); }
}