如何将ViewModel添加到使用ViewPager和Tablayout的项目中?

Muhittin Kaya

您好,我是Android开发的新手,所以这个问题可能对您来说很奇怪。

我有一个名为IdentityCardInfo的类,该类具有变量。我在InfoFragment中得到了这个变量

从InfoFragment,我想在ResultsFragment中显示这些变量,其中有3个选项卡具有tablayout。

我想使用ViewModel来将数据传递到布局,但是我不知道如何使用我搜索过但被卡住的东西。

这是IdentityCardInfo类的代码:

class IdentityCardInfo {

    companion object AppConstant{
        const val serieNo ="67G74444"
        const val validDate = "01/01/2022"
        const val dateOfBirth = "10/08/1998"
        const val fullName = "Muhittin KAYA"
        const val identityNo: Long = 11111111111
        const val gender = "MALE"
        const val nationality = "TUR"
    }
}

这是InfoFragment的代码:

class InfoFragment : BaseFragment() {

    lateinit var navController: NavController

    companion object {
        private const val TAG = "Info Fragment"
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_info, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        navController = Navigation.findNavController(view)
        button_info_idcard.setOnClickListener {
            //start OcrActivity
            val intent = Intent(activity, OcrActivity::class.java)
            startActivityForResult(intent, 101)
        }

        imagebutton_info_settings.setOnClickListener {
            navController.navigate(R.id.action_infoFragment_to_settingsFragment)
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        Log.i("Muhittin", "onActivityResult()")

        if (requestCode == 101) {
            val message = data?.getStringExtra("TEST_TEXT")
            Toast.makeText(context, message, Toast.LENGTH_SHORT).show()

            val serieNo = IdentityCardInfo.serieNo
            val validDate = IdentityCardInfo.validDate
            val dateOfBirth = IdentityCardInfo.dateOfBirth
            val fullname = IdentityCardInfo.fullName
            val gender = IdentityCardInfo.gender
            val identityNo = IdentityCardInfo.identityNo
            val nationality = IdentityCardInfo.nationality

            val bundle = bundleOf(
                "TEST_TEXT" to message,
                "SERIE_NO" to serieNo,
                "VALID_DATE" to validDate,
                "DOB" to dateOfBirth,
                "FULL_NAME" to fullname,
                "GENDER" to gender,
                "IDENTITY_NO" to identityNo,
                "NATIONALITY" to nationality
            )
            navController.navigate(
                R.id.action_infoFragment_to_detailFragment,
                bundle
            )
        }
    }
}

这是针对ResultsFragment的:(我不添加tablayout代码和viewpager代码)

class ResultsFragment : Fragment() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        retainInstance = true
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_results, container, false)
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        val tabLayout: TabLayout = requireView().findViewById(R.id.tabLayout_results)

        tabLayout.tabGravity = TabLayout.GRAVITY_FILL
        val tabTitles = arrayOf(
            resources.getString(R.string.result_tab1_name),
            resources.getString(R.string.result_tab2_name),
            resources.getString(R.string.result_tab3_name)
        )

        val viewPager: ViewPager = requireView().findViewById(R.id.viewpager_results)
        viewPager.offscreenPageLimit = 3
        val adapter = PagerAdapter(fragmentManager, tabTitles)
        viewPager.adapter = adapter
        tabLayout.setupWithViewPager(viewPager)
    }

}
马舒克汗

@muhittin kaya请参阅下面的代码来解决您的问题

信息片段

class InfoFragment : BaseFragment() {

    lateinit var navController: NavController

    // Initialize your variable
    lateinit var infoFragmentInterface: InfoFragmentDataInterface

    // If you get initialization exception then uncomment below line and comment above line
    //private var  infoFragmentInterface: InfoFragmentDataInterface? = null


    companion object {
        private const val TAG = "Info Fragment"
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_info, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        navController = Navigation.findNavController(view)
        button_info_idcard.setOnClickListener {
            //start OcrActivity
            val intent = Intent(activity, OcrActivity::class.java)
            startActivityForResult(intent, 101)
        }

        imagebutton_info_settings.setOnClickListener {
            navController.navigate(R.id.action_infoFragment_to_settingsFragment)
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        Log.i("Muhittin", "onActivityResult()")

        if (requestCode == 101) {
            val message = data?.getStringExtra("TEST_TEXT")
            Toast.makeText(context, message, Toast.LENGTH_SHORT).show()

            val serieNo = IdentityCardInfo.serieNo
            val validDate = IdentityCardInfo.validDate
            val dateOfBirth = IdentityCardInfo.dateOfBirth
            val fullname = IdentityCardInfo.fullName
            val gender = IdentityCardInfo.gender
            val identityNo = IdentityCardInfo.identityNo
            val nationality = IdentityCardInfo.nationality

            val bundle = bundleOf(
                "TEST_TEXT" to message,
                "SERIE_NO" to serieNo,
                "VALID_DATE" to validDate,
                "DOB" to dateOfBirth,
                "FULL_NAME" to fullname,
                "GENDER" to gender,
                "IDENTITY_NO" to identityNo,
                "NATIONALITY" to nationality
            )

            //Add This line for passing your data
            //You can also pass string data here
            infoFragmentInterface.getInfoFragmentData(bundle)

            navController.navigate(
                R.id.action_infoFragment_to_detailFragment,
                bundle
            )
        }
    }
}

// Create this interface to pass your data
interface InfoFragmentDataInterface {
    fun getInfoFragmentData(bundle: Any)
}

结果片段

class ResultsFragment : Fragment(), InfoFragmentDataInterface {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        retainInstance = true
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_results, container, false)
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        val tabLayout: TabLayout = requireView().findViewById(R.id.tabLayout_results)

        tabLayout.tabGravity = TabLayout.GRAVITY_FILL
        val tabTitles = arrayOf(
            resources.getString(R.string.result_tab1_name),
            resources.getString(R.string.result_tab2_name),
            resources.getString(R.string.result_tab3_name)
        )

        val viewPager: ViewPager = requireView().findViewById(R.id.viewpager_results)
        viewPager.offscreenPageLimit = 3
        val adapter = PagerAdapter(fragmentManager, tabTitles)
        viewPager.adapter = adapter
        tabLayout.setupWithViewPager(viewPager)
    }

    override fun getInfoFragmentData(bundle: Any) {
        // You'll get your Bundle data here.
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何将源项目添加到项目中

如何将browserify添加到yeoman项目中?

如何将点击分别添加到RecyclerView的整个行和特定的行项目中?

如何将图像添加到Xamarin.Forms共享项目的资源中,以便可以在Android和iOS项目中使用?

如何使用Razor和.NET Core将项目添加到ViewModel的列表中?

如何将gradle作为依赖项添加到子项目根项目中?

如何将Web Animations API polyfill添加到使用Angular CLI创建的Angular 2项目中

如何将包集合添加到我的 Xcode 项目中?

如何将BundleConfig.cs添加到我的项目中?

如何将android支持库添加到我的netbeans项目中

如何将Red Bean PHP正确添加到我的项目中

如何将libgdx添加到现有的android studio项目中?

如何将监视模块添加到现有的Android Studio项目中?

如何将Azure Active Directory组添加到SSDT表格项目中的角色?

如何将外部.exe添加到我的C#项目中?

如何将Google Play服务添加到我的Eclipse ADT项目中

如何将平台添加到现有Flutter应用程序/项目中?

如何将系统api类添加到非AOSP构建的android项目中

如何将真实文件夹添加到我的Netbeans C项目中?

如何将Groovy脚本添加到具有经典Maven结构的Java项目中?

如何将已编译的 C 代码添加到 android studio 项目中?

如何将Go代码添加到现有项目中

如何将打字稿添加到现有的 vue3 项目中?

如何将cdn css文件添加到Vue Cli 3项目中?

如何将com.typesafe.sbt。*依赖项添加到我的项目中?

如何将图像添加到netbeans Java项目中

如何将pdf文件添加到您的android项目中?

如何将-Xlint:uncheck添加到基于Android Gradle的项目中?

如何将pom.xml添加到现有的Eclipse项目中?