一Activity、二Fragment有共同点ViewModel。我已经验证每个片段中的视图模型引用都是相同的。
在片段一的布局 XML 中,有一个TextInputLayout. 片段二用布尔值更新视图模型。文本输入布局正在观察该值,并且应该BindingAdapter在该值更改时调用 a 。
当片段实例化并且它们的布局膨胀时,绑定适配器会触发,所以我知道视图正在观察这个值。但是,稍后,当片段二更新值时,片段一中的视图不会触发绑定适配器。
这是onCreateView()片段一中的内容:
registrationViewModel = activity?.run {
ViewModelProviders
.of(this, RegistrationViewModelFactory(prefs, dataFetcherService))
.get(RegistrationViewModel::class.java)
} ?: throw Exception("Invalid Activity")
Run Code Online (Sandbox Code Playgroud)
这是观察该视图模型的视图:
<com.google.android.material.textfield.TextInputLayout
android:id="@+id/reg_auth_code_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
bind:errorState="@{registrationViewModel.registrationData.authorizationError}"
bind:errorMessage="@{@string/invalid_auth_code}">
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/reg_auth_code"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@{registrationViewModel.registrationData.authCode}"
android:hint="@string/enter_auth_code"
android:maxLines="1"
android:inputType="text"
android:imeOptions="actionDone"
app:autoSizeTextType="uniform"/>
</com.google.android.material.textfield.TextInputLayout>
Run Code Online (Sandbox Code Playgroud)
至于片段二,onCreateView() 中的代码相同:
registrationViewModel = activity?.run {
ViewModelProviders
.of(this, RegistrationViewModelFactory(prefs, dataFetcherService))
.get(RegistrationViewModel::class.java)
} ?: throw Exception("Invalid Activity")
Run Code Online (Sandbox Code Playgroud)
单击按钮时,片段二会在视图模型中触发一个活动:
private fun attemptNavigationToUserData() {
viewModelScope.launch {
isAuthorized = runBlocking { …Run Code Online (Sandbox Code Playgroud) 我在使用 Kotlin 协程 + LiveData + DataBinding 时遇到问题。
我的代码如下
class TempViewModel: ViewModel() {
val creatorInfo: LiveData<CreatorInfo> = liveData(context = viewModelScope.coroutineContext + Dispatchers.IO) {
val data = CreatorInfoSettingRepository.requestCreatorInfo().body()
emit(data!!)
}
}
Run Code Online (Sandbox Code Playgroud)
和 xml 像这样使用数据绑定
<TextView
android:text="@{viewModel.creatorInfo.email}" />
<TextView
android:text="@{viewModel.creatorInfo.phone}" />
....
Run Code Online (Sandbox Code Playgroud)
我检查从服务器(retrofit2)获取数据(CreatorInfo)是否成功,但数据未通过数据绑定应用于UI。
另外,当像下面这样检查观察时,观察块也会被调用。
viewModel.creatorInfo.observe(fragment, Observer { creatorInfo ->
Log.d("ssong","test")
})
Run Code Online (Sandbox Code Playgroud)
有谁可以帮忙吗?
android kotlin android-databinding android-livedata kotlin-coroutines
请帮帮我。
我想使用LiveData.
OnChanged()在应用程序启动时触发一次,但是当我string1通过单击按钮更改值时,onChange()不会触发并且信息不会更新。TextView一直显示“哇”
我完全按照这里的描述做所有事情。
的ViewModel:
class CurrentViewModel : ViewModel() {
val currentName: MutableLiveData<String> by lazy {
MutableLiveData<String>()
}
}
Run Code Online (Sandbox Code Playgroud)
片段:
class CurrentFragment : Fragment(R.layout.current_fragment) {
private val viewModel: CurrentViewModel by viewModels()
var string1 = "Wow!"
override fun onActivityCreated(savedInstanceState: Bundle?)
val nameObserver = Observer<String> { newName ->
textview.text = newName }
viewModel.currentName.value = string1
viewModel.currentName.observe(activity!!, nameObserver)
button.setOnClickListener {
string1 = "some new string"
}
}
Run Code Online (Sandbox Code Playgroud) 我正在通过https://github.com/googlecodelabs/android-room-with-a-view/tree/kotlin的示例项目 RoomWordsSample 学习 Room。
以下代码来自项目。
在我看来,如果观察到数据发生变化,LiveDate 将自动更新 UI。
但是在文件 WordListAdapter.kt 中,我发现notifyDataSetChanged()添加到function setWords(words: List<Word>)? 似乎它必须在数据更改时手动通知 UI。
为什么还需要启动 notifyDataSetChanged()当我使用 LiveData 时,?
主活动.kt
class MainActivity : AppCompatActivity() {
private val newWordActivityRequestCode = 1
private lateinit var wordViewModel: WordViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val recyclerView = findViewById<RecyclerView>(R.id.recyclerview)
val adapter = WordListAdapter(this)
recyclerView.adapter = adapter
recyclerView.layoutManager = LinearLayoutManager(this)
wordViewModel = ViewModelProvider(this).get(WordViewModel::class.java)
wordViewModel.allWords.observe(this, Observer { words ->
words?.let { adapter.setWords(it) }
})
}
}
Run Code Online (Sandbox Code Playgroud)
WordViewModel.kt …
在以下示例中,我想公开这样的 Int 列表:
val test: LiveData<List<Int>>
get() = _test as LiveData<List<Int>>
private var _test = MutableLiveData(mutableListOf<Int>())
Run Code Online (Sandbox Code Playgroud)
或另一种口味:
private var _test2 = MutableLiveData(mutableListOf<Int>())
val test2 = _test2 as LiveData<List<Int>>
Run Code Online (Sandbox Code Playgroud)
两者都在工作,但总是有一个未经检查的演员。
Unchecked cast: MutableLiveData<MutableList<Int>!> to LiveData<List<Int>>
Run Code Online (Sandbox Code Playgroud)
有没有更好的方法来做到这一点?
只是为了澄清:
通过使用 emptyList,用法可能如下所示:
class MainViewModel : ViewModel() {
val test: LiveData<List<Int>> get() = _test
private var _test = MutableLiveData(emptyList<Int>())
init {
val myPrivateList = mutableListOf<Int>()
myPrivateList.add(10)
myPrivateList.add(20)
_test.value = myPrivateList
}
}
Run Code Online (Sandbox Code Playgroud)
我希望找到一种无需额外列表(myPrivateList)的方法,如下所示:
class MainViewModel : ViewModel() {
val test: LiveData<List<Int>> get() = _test
private …Run Code Online (Sandbox Code Playgroud) 我试图实现分页,但每次我旋转视图模型的屏幕构造函数时都会被调用,从而触发 loadInitial 从我的 DataSource 类中的网络获取新数据。感谢帮助
// ViewModel
def lifecycle_version = "2.2.0"
implementation "androidx.lifecycle:lifecycle-viewmodel:$lifecycle_version"
// LiveData
implementation "androidx.lifecycle:lifecycle-livedata:$lifecycle_version"
Run Code Online (Sandbox Code Playgroud)
在我的活动 oncreate 中:
TopRatedResultViewModel viewModel = ViewModelProvider.AndroidViewModelFactory.getInstance(getApplication()).create(TopRatedResultViewModel.class);
Run Code Online (Sandbox Code Playgroud)
查看型号:
public class TopRatedResultViewModel extends AndroidViewModel {
private Top_Rated_Results_Repository repository;
public TopRatedResultViewModel(@NonNull Application application) {
super(application);
Log.d("moviedatabaselog", "TopRatedResultViewModel ");
repository = new Top_Rated_Results_Repository(application);
}
public LiveData<PagedList<Top_Rated_Result>> getTopRatedResultsPagedList() {
return repository.getTopRatedResultsPagedList();
}
Run Code Online (Sandbox Code Playgroud)
我正在关注本教程Android 分页与改造, 但这里使用了不推荐使用的 ViewModelProviders.of 并且当我在屏幕旋转构造函数没有被调用后测试它时。
android android-mvvm android-livedata android-architecture-components
我需要更改 ViewModel 中 MutableLiveData 的值,但我无法做到这一点,因为该值等于 null,我认为需要建立一个观察者在其中更改它,但我不知道该怎么做,并且这是否是一个好主意。
录音机列表视图模型
class AudioRecordersListViewModel() : ViewModel() {
var audioRecordsLiveData: MutableLiveData<MutableList<AudioRecordUI>> = MutableLiveData();
private var audioRecordDao: AudioRecordDao? = null
@Inject
constructor(audioRecordDao: AudioRecordDao) : this() {
this.audioRecordDao = audioRecordDao
viewModelScope.launch {
val liveDataItems = audioRecordDao
.getAll().value!!.map { item -> AudioRecordUI(item) }
.toMutableList()
if (liveDataItems.size > 0) {
liveDataItems[0].isActive = true
}
audioRecordsLiveData.postValue(liveDataItems)
}
}
}
Run Code Online (Sandbox Code Playgroud)
录音道
@Dao
interface AudioRecordDao {
@Query("SELECT * FROM AudioRecordEmpty")
fun getAll(): LiveData<MutableList<AudioRecordEmpty>>
}
Run Code Online (Sandbox Code Playgroud) 我的数据仅在创建时才获取...我使用视图模型...当按后退按钮时,它不会更新以前的数据..onresume 在此不起作用...
我引用了这个,但这些都没有帮助-->对 ViewModel 中的活动生命周期做出反应
我需要帮助
提前致谢
活动: -
class MyAccount : BaseClassActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.myaccount)
var mActionBarToolbar = findViewById<androidx.appcompat.widget.Toolbar>(R.id.toolbartable);
setSupportActionBar(mActionBarToolbar);
setEnabledTitle()
val resetbutton=findViewById<Button>(R.id.resetpwd)
resetbutton.setOnClickListener {
val i=Intent(applicationContext,
ResetPasswordActivity::class.java)
startActivity(i)
}
val editbutton=findViewById<Button>(R.id.editdetail)
editbutton.setOnClickListener {
val i=Intent(applicationContext, EditProfile::class.java)
startActivity(i)
}
hello()
}
override fun onResume() {
super.onResume()
hello()
}
fun hello(){
val first_name = findViewById<TextView>(R.id.firstname)
val last_name = findViewById<TextView>(R.id.lastname)
val emailuser = findViewById<TextView>(R.id.emailuser)
val phone_no = findViewById<TextView>(R.id.phone_no)
val birthday = findViewById<TextView>(R.id.birthday)
val image=findViewById<ImageView>(R.id.imageprofile)
val …Run Code Online (Sandbox Code Playgroud) 到目前为止,我一直在使用Flow并将其映射到LiveData如下所示 -
看起来MyService像这样——
override fun provideData(action: MyAction) = flow {
emit(MyResult.Loading)
emit(dataRepository.getNewData())
}
Run Code Online (Sandbox Code Playgroud)
看起来ViewModel像这样——
fun getData() = myService.provideData(MyAction.GetData).map {
}.asLiveData(Dispatchers.Default + viewModelScope.coroutineContext)
Run Code Online (Sandbox Code Playgroud)
我想搬到StateFlow. 我怎样才能emit像StateFlow使用Flow.
有没有办法MediatorLiveData用初始值进行初始化?我想实现如下目标:
val myLiveData = MediatorLiveData<String>("initial value")
Run Code Online (Sandbox Code Playgroud)
有一个构造函数,MutableLiveData它根据文档采用初始值,但是有没有办法为 做同样的事情MediatorLiveData?
android ×10
android-livedata ×10
kotlin ×8
viewmodel ×2
android-architecture-components ×1
android-mvvm ×1
lifecycle ×1
mvvm ×1