簡體   English   中英

從 MainActivity class 將新字符串注入 Fragment/ViewModel

[英]Inject new string into Fragment/ViewModel from MainActivity class

使用 android 工作室底部導航活動模板,希望我的HomeFragment / HomeViewModel頁面文本在每次從底部導航訪問主頁時更改。 當我第一次單擊它時,它顯示的文本應該與第二次顯示的文本不同。

我能夠創建一個包含文本 output 的變量,並且我創建了一個 function 應該能夠更新該變量,但我無法在MainActivity ZA2F2ED4F8EBC2CBB4C21A29D 中調用它。 有任何想法嗎?

主要活動

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val navView: BottomNavigationView = findViewById(R.id.nav_view)
        val navController = findNavController(R.id.nav_host_fragment)
        val appBarConfiguration = AppBarConfiguration(setOf(
                R.id.navigation_home, R.id.navigation_dashboard, R.id.navigation_notifications))


        navView.setupWithNavController(navController)
    }

首頁片段

class HomeFragment : Fragment() {

    private lateinit var homeViewModel: HomeViewModel
    var chosenOutput:String = "primary output";

    override fun onCreateView(
            inflater: LayoutInflater,
            container: ViewGroup?,
            savedInstanceState: Bundle?
    ): View? {
        //using update here crashes the app
        homeViewModel =
                ViewModelProvider(this).get(HomeViewModel::class.java)
        val root = inflater.inflate(R.layout.fragment_home, container, false)
        val textView: TextView = root.findViewById(R.id.text_home)
        homeViewModel.text.observe(viewLifecycleOwner, Observer {
            textView.text = chosenOutput; //changing 'chosenOutput' to 'it' means that text update must take place within HomeViewModel instead of fragment.
        })
       
        return root
    }
    fun update(result: String)
    {
        chosenOutput = result; 
    }
}

主頁查看模型

class HomeViewModel : ViewModel() {
    var temp:String = "demo"
    //constructor()
    private val _text = MutableLiveData<String>().apply {
        value = temp;
    }
    fun update(result: String) //function may be obsolete if text change can be done in fragment.
    {
        temp = result; 
    }
    val text: LiveData<String> = _text

}

從我給出的MainActivity class 將字符串注入FragmentViewModel的正確方法是什么?

您可以更改方法並將您的chosenOutput變量存儲在MainActivity中,並在您每次 select HomeFragment時更新它

class MainActivity : AppCompatActivity() 
{
    var chosenOutput = "primary output"
    ...

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val navView: BottomNavigationView = findViewById(R.id.nav_view)
        val navController = findNavController(R.id.nav_host_fragment)
        val appBarConfiguration = AppBarConfiguration(setOf(
                R.id.navigation_home, R.id.navigation_dashboard, R.id.navigation_notifications))

        navView.apply {
            setupWithNavController(navController)

            setOnNavigationItemSelectedListener { menuItem ->
                when (menuItem.itemId) {
                    R.id.navigation_home -> {
                        chosenOutput = "new value" // <-- Update chosen output here
                        // Add this method to call the `onResume` method in the fragment
                        showFragment(HomeFragment.newInstance())
                    }
                    else { }
                }

                true
        }
    }

    private fun showFragment(fragment: Fragment) {
        supportFragmentManager.beginTransaction()
                .replace(R.id.nav_host_fragment, fragment)
                .addToBackStack(null)
                .commit()
    }
}

然后,您可以使用此代碼在Fragment中檢索更新的字符串。 請注意,我添加了companion object以避免創建Fragment的多個實例。

class HomeFragment : Fragment() 
{
    companion object
    {
        fun newInstance() : HomeFragment
        {
            return HomeFragment()
        }
    }

    override fun onResume() {
        super.onResume()

        val newChosenOutput = (activity as MainActivity).chosenOutput
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM