Android笔记
——选项卡与滑动界面 【若对该知识点有更多想了解的,欢迎私信博主~~】
选项卡与滑动界面:FragmentTabHost and ViewPager
FragmentTabHost :
第一步:在Activity布局文件中添加FragmentTabHost控件
<?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"
android
:orientation
="vertical"
tools
:context
=".MainActivity">
<!--选项卡
-->
<android
.support
.v4
.app
.FragmentTabHost
android
:id
="@+id/tab"
android
:layout_width
="match_parent"
android
:layout_height
="100dp">
</android
.support
.v4
.app
.FragmentTabHost
>
<!--承载碎片的容器
-->
<FrameLayout
android
:id
="@+id/fl"
android
:layout_width
="match_parent"
android
:layout_height
="match_parent">
</FrameLayout
>
</LinearLayout
>
第二步:在Activity中初始化
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState
) {
super.onCreate(savedInstanceState
);
setContentView(R
.layout
.activity_main
);
FragmentTabHost tabHost
=findViewById(R
.id
.tab
);
tabHost
.setup(this,getSupportFragmentManager(),R
.id
.fl
);
tabHost
.addTab(tabHost
.newTabSpec("1").setIndicator("1"),Fragment1
.class,null
);
tabHost
.addTab(tabHost
.newTabSpec("2").setIndicator("2"),Fragment2
.class,null
);
}
}
ViewPager:
第一步:在Activity布局文件中添加VieewPager控件
<?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">
<android
.support
.v4
.view
.ViewPager
android
:layout_width
="match_parent"
android
:layout_height
="match_parent"
android
:id
="@+id/vp">
</android
.support
.v4
.view
.ViewPager
>
</LinearLayout
>
第二步:创建ViewPager适配器,继承FragmentPagerAdapter
public class FragmentViewPagerAdapter extends FragmentPagerAdapter {
List
<Fragment> list
;
public FragmentViewPagerAdapter(FragmentManager fm
,List
<Fragment> list
) {
super(fm
);
this.list
=list
;
}
@Override
public Fragment
getItem(int i
) {
return list
.get(i
);
}
@Override
public int getCount() {
return list
!=null
?list
.size():0;
}
}
第三步:在Activity中初始化
public class MainActivity extends AppCompatActivity {
ViewPager vp
;
FragmentViewPagerAdapter vpa
;
@Override
protected void onCreate(Bundle savedInstanceState
) {
super.onCreate(savedInstanceState
);
setContentView(R
.layout
.activity_main
);
vp
=findViewById(R
.id
.vp
);
FragmentManager fm
=getSupportFragmentManager();
List
<Fragment> list
=new ArrayList<>();
list
.add(new Fragment1());
list
.add(new Fragment2());
vpa
=new FragmentViewPagerAdapter(fm
,list
);
vp
.setAdapter(vpa
);
vp
.setCurrentItem(0);
}
}