本文介绍了如何考虑片段和活动的创建顺序来管理片段和活动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从Fragment调用Activity,以在Android应用程序中同时实现片段和活动之间的转换.

I would like to call Activity from Fragment to realize both transitions among fragments and activities simultaneously in an Android app.

我已经成功地从片段文件中调用了活动文件上的一种特定方法,但是我无法从片段中调用整个活动.

I have succeeded to call one specific method on activity file from fragment file, but I have trouble with calling an entire activity from a fragment.

SampleFragment - MainActivity's fragmentMethod() is called once  the button is clicked on the page
Sample1Fragment - FormActivity is called once the button is clicked on the page
FormActivity - FormActivity2 is called once the button is clicked on the page

以上与我以前的问题相同:

The above is same as my former question: How can I fix the code to call Activity from Fragment in Android App?

成功构建了一个项目并在模拟器上运行该应用程序.但是,当我单击按钮以调用Sample1Fragment上的FormActivity时,屏幕突然关闭.

It was succeeded to build a project and run the app on the emulator. However, the screen was suddenly shut down when I click the button to call FormActivity on Sample1Fragment.

我无法解决此问题.

错误消息发送到Sample1Fragment.kt的以下部分

Error Message to the below part on Sample1Fragment.kt

Modifier 'override' is not applicable to 'local function'

Sample1Fragment.kt

Sample1Fragment.kt

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

        override fun onViewCreated(view: View, savedInstanceState: Bundle) {
            btnClick2.setOnClickListener(object:View.OnClickListener{

                // here I would like to move to FormActivity
                override fun onClick(v: View?) {
                    activity?.startActivity(Intent(context, FormActivity::class.java))
                }

            })
        }

当前代码

MainActivity.kt

Current Code

MainActivity.kt

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import androidx.fragment.app.Fragment
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        // make the list of fragment
        val fragmentList = arrayListOf<Fragment>(
            SampleFragment(),
            Sample1Fragment()
        )

        // create instance of adapter
        val adapter = SamplePagerAdapter(supportFragmentManager, fragmentList)
        /// set adapter
        viewPager.adapter = adapter
    }



    public fun fragmentMethod() {
        Toast.makeText(this@MainActivity, "Method called From Fragment", Toast.LENGTH_LONG).show();
    }
}

SampleFragment.kt

SampleFragment.kt

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import kotlinx.android.synthetic.main.fragment_sample.*

class SampleFragment : Fragment() {


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {

        }
    }

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

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        btnClick.setOnClickListener(object:View.OnClickListener{
            override fun onClick(v: View?) {
                (activity as MainActivity).fragmentMethod()
            }

        })
    }



}

Sample1Fragment.kt

Sample1Fragment.kt

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import kotlinx.android.synthetic.main.fragment_sample1.*
import android.content.Intent

class Sample1Fragment : Fragment() {

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

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

        override fun onViewCreated(view: View, savedInstanceState: Bundle) {
            btnClick2.setOnClickListener(object:View.OnClickListener{

                // here I would like to move to FormActivity
                override fun onClick(v: View?) {
                    activity?.startActivity(Intent(context, FormActivity::class.java))
                }

            })
        }

    }

}

开发环境

Android Studio 3.6.1

Developping Environment

Android Studio 3.6.1

它试图在答案中使用推荐的SingleLiveEvent,但是我还没有找到在当前代码ListViewModel.ktSample1Fragment.kt上实现它的合适方法.

It tried to use SingleLiveEvent recommended on an answer, but I haven't found the appropriate way to implement it on my current code, ListViewModel.kt and Sample1Fragment.kt.

参考: LiveData SnackBar,导航和其他事件(SingleLiveEvent案例)

ListViewModel.kt

ListViewModel.kt

import android.app.usage.UsageEvents
import android.os.Build
import androidx.annotation.RequiresApi
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel

class ListViewModel : ViewModel() {
    private val _navigateToDetails = MutableLiveData<UsageEvents.Event<String>>()

    val navigateToDetails : LiveData<UsageEvents.Event<String>>
        get() = _navigateToDetails


    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    fun userClicksOnButton(itemId: String) {
        _navigateToDetails.value =
            UsageEvents.Event(itemId)  // Trigger the event by setting a new Event as a new value
    }
}

这些是我面临的错误消息

These are the error messages I'm facing to

Sample1Fragment.kt

Sample1Fragment.kt

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import kotlinx.android.synthetic.main.fragment_sample1.*
import android.content.Intent


class Sample1Fragment : Fragment() {

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

    myViewModel.navigateToDetails.observe(this, Observer {
        it.getContentIfNotHandled()?.let { // Only proceed if the event has never been handled
        fun onViewCreated(view: View, savedInstanceState: Bundle) {
            btnClick2.setOnClickListener(object:View.OnClickListener{

                // here I would like to move to FormActivity
                override fun onClick(v: View?) {
                    activity?.startActivity(Intent(context, FormActivity::class.java))
                }

            })
        }
    })

    }

}

这是我面临的错误消息

推荐答案

Sample1Fragment.kt中,您将覆盖onViewCreated() 内部 onActivityCreated()方法.
这就是为什么

In Sample1Fragment.kt you are overriding onViewCreated() inside onActivityCreated() method.
This is why you get


关于导航:有几种方法可以在不同的活动和片段之间进行导航:


About navigation:there is several possible ways how to navigate between different activities and fragments:

  1. n
  2. 回调,当您在Android中创建片段时已经对其进行了预先设置工作室
  3. 视图模型,在片段及其活动之间共享.在这种情况下,我建议使用 SingleLiveEvent 触发事件.
  1. navigation, which is usually the easiest to implement
  2. callbacks, which are already preset when you create a fragment in Android Studio
  3. view model, shared between fragment and it's activity. In this case, I suggest using SingleLiveEvent to trigger the event.

这篇关于如何考虑片段和活动的创建顺序来管理片段和活动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-09 08:18