将片段添加到 Android 开发者工作室的选项卡式活动模板



初学者在这里。使用 Android 开发者工作室选项卡式活动模板创建应用。我有两个xml,模板和第二个选项卡附带的生成的fragment_main.xml.xml用于我想成为第二个选项卡的内容。

这是模板生成的代码:

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val sectionsPagerAdapter = SectionsPagerAdapter(this, supportFragmentManager)
val viewPager: ViewPager = findViewById(R.id.view_pager)
viewPager.adapter = sectionsPagerAdapter
val tabs: TabLayout = findViewById(R.id.tabs)
tabs.setupWithViewPager(viewPager)
val fab: FloatingActionButton = findViewById(R.id.fab)
fab.setOnClickListener { view ->
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show()
}

我一直在通读 ViewPager 文档,我能找到的很多内容都是从头开始制作的,我很难理解。我觉得我错过了一些明显的东西。如何将我的第二个选项卡.xml添加到此预生成的模板中,以便在用户单击第二个选项卡时显示它?

你的部分PagerAdaptergetItem函数应该看起来像这样:

class SectionsPagerAdapter(
private val context: Context,
fm: FragmentManager
) : FragmentPagerAdapter(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) {
override fun getItem(position: Int) = when (position) {
0 -> FirstTabFragment()
1 -> SecondTabFragment()
else -> error("Unknown")
}
override fun getPageTitle(position: Int) = context.resources.getString(TAB_TITLES[position])
override fun getCount() = 2
}

因为默认情况下,在此模板中SectionsPagerAdapter始终创建占位符片段:

override fun getItem(position: Int): Fragment {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return PlaceholderFragment.newInstance(position + 1)
} 

但是在你的例子中,你需要使用两个不同的片段和两个不同的xml布局,如下所示:

class FirstTabFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val root = inflater.inflate(R.layout.fragment_main, container, false)
val textView: TextView = root.findViewById(R.id.section_label)
return root
}
}
class SecondTabFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val root = inflater.inflate(R.layout.secondtab, container, false)
val textView: TextView = root.findViewById(R.id.section_label)
return root
}
}

还要确保添加:

<TextView
android:id="@+id/section_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="@dimen/activity_horizontal_margin"
android:layout_marginTop="@dimen/activity_vertical_margin"
android:layout_marginEnd="@dimen/activity_horizontal_margin"
android:layout_marginBottom="@dimen/activity_vertical_margin"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="@+id/constraintLayout"
tools:layout_constraintLeft_creator="1"
tools:layout_constraintTop_creator="1" />

到片段 XML

最新更新