我想在我的改编中添加更多Fragment
页面,但我不知道该怎么做。
这是我的代码adpater与单Fragment
,没有问题。
提前感谢您的帮助
class TabAdapter(fragmentManager: FragmentManager) : FragmentPagerAdapter(fragmentManager) {
override fun getItem(position: Int) = SampleFragment() //SampleFragment() is my fragment
override fun getCount() = 4
override fun getPageTitle(position: Int) = when (position) {
0 -> "Music"
1 -> "Market"
2 -> "Films"
else -> "Books"
}
}
这是我的SampleFragment()
class SampleFragment : Fragment() {
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
return inflater!!.inflate(R.layout.fragment_sample, container, false)
}
}
请帮助我为Fragment
Adapter
答案 0 :(得分:0)
以下是如何快速将片段添加到适配器中。
您需要ViewPager来保存您想要显示的所有片段。
首先按如下方式编辑你的xml。
<RelativeLayout
android:id="@+id/main_layout"
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="wrap_content"
tools:context=".MainActivity">
<ViewPager
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/tab_layout" />
<android.support.design.widget.TabLayout
android:id="@+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:elevation="6dp"
android:minHeight="?attr/actionBarSize"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"/>
</RelativeLayout>
下一步创建新片段并将其命名为Fragment_one.java
。在这里,你可以做任何你喜欢的活动。创建Fragment_two.java
或任意多个,并在适配器中实例化它。
接下来创建fragmentAdapter.Java
并添加这些代码(这适用于您的自定义适配器)
public class fragmentAdapter extends FragmentStatePagerAdapter {
int mNumOfTabs;
public fragmentAdapter(FragmentManager fm, int NumOfTabs){
super(fm);
this.mNumOfTabs = NumOfTabs;
}
@Override
public Fragment getItem(int position) {
// Add as many fragment in this method
switch (position){
case 0:
Fragment_one frag_one = new Fragment_one ();
return frag_one;
case 1:
Fragment_two frag_two = new Fragment_two ();
return frag_two;
default:
return null;
}
}
@Override
public int getCount() {
return mNumOfTabs;
}
}
接下来在onCreate()
MainActivity.java
方法
TabLayout tabLayout = (TabLayout) view.findViewById(R.id.tab_layout);
//add as many fragments you want to add the "fragment 1" & "fragment 2" is
//the title for your fragments, it starts for '0','1','2'...
tabLayout.addTab(tabLayout.newTab().setText("fragment 1"));
tabLayout.addTab(tabLayout.newTab().setText("fragment 2"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
final fragmentAdapter adapter = new Adapter(getActivity(),tablayout.geTabCount());
viewPager.setAdapter(adapter);