gpt4 book ai didi

android - Kotlin 如何在 fragment 内设置 tablayout(viewpager 不工作)

转载 作者:行者123 更新时间:2023-11-29 22:47:56 27 4
gpt4 key购买 nike

我正在尝试在 fragment 中创建 tablayout。出于某种原因,我的 viewpager 无法正常工作。它一直显示与下面相同的错误

enter image description here

我的 fragment 代码和xml文件如下

package com.example.rsquare_android_fixed.mywork.building

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.viewpager.widget.ViewPager
import com.example.rsquare_android_fixed.R
import kotlinx.android.synthetic.main.fragment_mywork.*


class MWFragment: Fragment(){
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
//val view=inflater.inflate(R.layout.fragment_mywork, container, false)

Log.d("test","test")

//vp_main.adapter=MW_Adapter(childFragmentManager)
val fa=MW_Adapter(childFragmentManager)
vp_main.adapter=fa
tab_layout.setupWithViewPager(vp_main)

return inflater.inflate(R.layout.fragment_mywork, container, false)
}

}

xml

<?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"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">

<com.google.android.material.appbar.AppBarLayout
android:theme="@style/TabTheme"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.google.android.material.tabs.TabLayout
android:id="@+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</com.google.android.material.appbar.AppBarLayout>

<androidx.viewpager.widget.ViewPager
android:id="@+id/vp_main"
android:layout_width="match_parent"
android:layout_height="match_parent"/>

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:text="hi"/>

</LinearLayout>

but if i try same codes on mainactivity it works well ...

最佳答案

问题是 kotlin 的扩展还不知道你的 fragment View 因为它在内部调用 getView 以在您使用的位置返回 null 的 fragment 中查找 View 尝试在 onViewCreated 中使用 vp_main 而不是 onCreateView

关于android - Kotlin 如何在 fragment 内设置 tablayout(viewpager 不工作),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58164541/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com