Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
321 views
in Technique[技术] by (71.8m points)

android - How to create a shared variable between fragments in kotlin

currently, my Kotlin based application consists of a single activity, 3 fragments and a navigation (with navigation drawer) between them.

How do I add a variable, which will be initialized in the start of the application, will be visible in all fragments, and can be updated in one of them? a simple int or string for that matter so it should be with little overhead as possible, yet i'd like to follow correct coding conventions. Please elaborate on the correct function to perform the initial variable value, how to bind each fragment textview to it, and the correct way to set the new value.

Thanks!

question from:https://stackoverflow.com/questions/65882249/how-to-create-a-shared-variable-between-fragments-in-kotlin

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Create ViewModel and fragments use viewmodel like this

val viewModel: YourViewModel by activityViewModels()

in that case your viewmodel's scope is the same as activity scope. For more information please refer to this link


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...