我是开发Android应用程序的新手,我正在尝试以"正确的方式"做所有事情.所以现在,我正在将新的Android Paging Library实现到我的项目中,我需要从网络服务器加载文章列表.
我有一个ArticlesRepository类,它返回一个ArticleList包含ArticleListItem我想在RecyclerView中显示的实例的类.文章列表已经分页的服务器上,这样仓库发送对第一页的请求,并返回一个ArticleList与page属性设置为1与articles包含属性List<ArticleListItem>的请求页面上的文章.我不知道一页上有多少篇文章.
现在,我能够实现一个PageKeyedDataSource<Integer, ArticleListItem>,但它只获取第一页:
@Override
public void loadInitial(@NonNull LoadInitialParams<Integer> params, @NonNull LoadInitialCallback<Integer, ArticleListItem> callback) {
ArticleList list = load(1);
if (list != null) {
callback.onResult(list.articles, null, next(list));
}
}
@Override
public void loadBefore(@NonNull LoadParams<Integer> params, @NonNull LoadCallback<Integer, ArticleListItem> callback) {
ArticleList list = load(previous(params.key));
if (list != null) {
callback.onResult(list.articles, previous(list));
}
}
@Override
public void loadAfter(@NonNull LoadParams<Integer> params, @NonNull …Run Code Online (Sandbox Code Playgroud) java android android-recyclerview android-viewmodel android-paging
阅读本文后,我得到了一些关于ViewModels的问题:
https://developer.android.com/topic/libraries/architecture/saving-states
它在这里说你应该结合使用a来ViewModel进行配置更改(比如屏幕旋转),并使用onSaveInstanceState()所有其他情况来销毁活动,然后重新创建以保存UI状态.
我的问题是我们如何知道onCreate(Bundle)调用时恢复状态的方法- 我应该使用ViewModel还是应该使用收到的包作为参数?当配置发生变化时,onSaveInstanceState()也会调用,显然onCreate()总是被调用.
如果我只从ViewModel恢复状态,它将不会始终保留正确的数据(因为活动可能由于配置更改之外的其他原因而被破坏).如果我只使用我保存的包onSaveInstanceState()那么为什么我会用a ViewModel开头?
android persistence android-activity android-mvvm android-viewmodel
我正在我的 Android 应用程序中创建自己的视图模型。
\n当应用程序启动时,它崩溃了,我收到了错误
\n\n“由以下原因引起:java.lang.NoSuchMethodException:[class android.app.Application]”
\n
1.查看模型类:
\npublic class MainViewModel extends AndroidViewModel implements OnCommunicationListener {\n \npublic MainViewModel(@NonNull Application application, DeviceData deviceData) {\n super(application);\n\n\xe2\x80\xa6.\n}\nRun Code Online (Sandbox Code Playgroud)\n2.查看模型工厂
\npublic class ViewModelFactory extends ViewModelProvider.AndroidViewModelFactory {\n\n @NonNull\n private final Application application;\n private final DeviceData deviceData;\n\n public ViewModelFactory(@NonNull Application application, DeviceData deviceData) {\n super(application);\n this.application = application;\n this.deviceData = deviceData;\n }\n\n @NonNull\n @Override\n public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {\n if (modelClass.isAssignableFrom(MainViewModel.class)) {\n return (T) new MainViewModel(application, deviceData);\n …Run Code Online (Sandbox Code Playgroud) 我在这里阅读了如何使用协程https://developer.android.com/topic/libraries/architecture/coroutines。是什么让我感到困惑的是之间的差异LiveDataScope和ViewModelScope。听起来像是ViewModelScope自动处理生命周期,您可以在块中进行网络请求。当从服务器收到数据时,将值发布到livedata. 但是当我继续阅读时,还有另一个主题对LiveDataScope我来说似乎是多余的,因为您已经可以通过使用ViewModelScopewith来完成相同的结果livedata。这两者之间的主要区别是什么?我什么时候应该选择使用一个而不是另一个?
android android-livedata android-viewmodel kotlin-coroutines
我正在尝试在 MainActivity 中创建我的 AndroidViewModel 实例。当我这样做时,我得到以下错误没有零参数构造函数
这是我的 RecipeViewModel
package com.example.kookrecepten;
import android.app.Application;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import java.util.List;
public class RecipeViewModel extends AndroidViewModel {
private RecipeRepository recipeRepository;
private LiveData<List<Recipe>> allRecipes;
public RecipeViewModel(Application application) {
super(application);
recipeRepository = new RecipeRepository(application);
allRecipes = recipeRepository.getAllRecipes();
}
public void insert(Recipe recipe) {
recipeRepository.insert(recipe);
}
public void update(Recipe recipe) {
recipeRepository.update(recipe);
}
public void delete(Recipe recipe) {
recipeRepository.delete(recipe);
}
public void deleteAll() {
recipeRepository.deleteAllRecipes();
}
public LiveData<List<Recipe>> getAllRecipes() {
return allRecipes;
}
}
Run Code Online (Sandbox Code Playgroud)
如果我错了,现在纠正我,但 AndroidViewModel …
java android android-lifecycle android-studio android-viewmodel
在探索 Dagger-Hilt 的 ViewModelInject 时,我遵循https://developer.android.com/training/dependency-injection/hilt-jetpack#viewmodels 中的示例
我尝试将 ViewModel 注入到我的活动中,如下所示
import android.app.Application
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.activity.viewModels
import androidx.hilt.Assisted
import androidx.hilt.lifecycle.ViewModelInject
import androidx.lifecycle.*
import androidx.savedstate.SavedStateRegistryOwner
import dagger.hilt.android.AndroidEntryPoint
import dagger.hilt.android.HiltAndroidApp
import kotlinx.android.synthetic.main.activity_main.*
import javax.inject.Inject
import javax.inject.Singleton
@HiltAndroidApp
class MainApplication: Application()
@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
private val viewModel: MyViewModel by viewModels()
private val textDataObserver =
Observer<String> { data -> text_view.text = data }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
viewModel.showTextDataNotifier.observe(this, textDataObserver)
btn_fetch.setOnClickListener { viewModel.fetchValue() }
}
} …Run Code Online (Sandbox Code Playgroud) 我想知道如何在将 Hilt 用于 DI 时将运行时参数传递给 ViewModel 的构造函数?在使用 Hilt 之前,我有一个如下所示的 ViewModel:
class ItemViewModel(private val itemId: Long) : ViewModel() {
private val repo = ItemRepository(itemId)
}
class ItemViewModelFactory(private val itemId: Long) : ViewModelProvider.Factory {
@Suppress("unchecked_cast")
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
if (modelClass.isAssignableFrom(ItemViewModel::class.java)) {
return ItemViewModel(itemId) as T
}
throw IllegalArgumentException("Unknown ViewModel class")
}
Run Code Online (Sandbox Code Playgroud)
我在我的片段中创建了上面的 ViewModel,如下所示:
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val args: ItemScreenFragmentArgs by navArgs()
val itemId = args.itemId
//Create the view model …Run Code Online (Sandbox Code Playgroud) android dependency-injection android-fragments android-viewmodel dagger-hilt
HomeScreen我想在预览功能中预览可组合功能HomeScreenPrevieiw。但是这是不可能的,因为我收到以下错误:
java.lang.IllegalStateException: ViewModels creation is not supported in Preview
at androidx.compose.ui.tooling.ComposeViewAdapter$FakeViewModelStoreOwner$1.getViewModelStore(ComposeViewAdapter.kt:709)
at androidx.lifecycle.ViewModelProvider.<init>(ViewModelProvider.kt:105)
at androidx.lifecycle.viewmodel.compose.ViewModelKt.get(ViewModel.kt:82)
at androidx.lifecycle.viewmodel.compose.ViewModelKt.viewModel(ViewModel.kt:72)
at com.example.crud.ui.screens.home.HomeScreenKt.HomeScreen(HomeScreen.kt:53)
at com.example.crud.ui.screens.home.HomeScreenKt.HomeScreenPreview(HomeScreen.kt:43)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
...
Run Code Online (Sandbox Code Playgroud)
这是我的HomeScreen代码:
@Composable
fun HomeScreen(
viewModel: HomeViewModel = hiltViewModel(),
navigateToDetailsAction: () -> Unit,
openCardDetailsAction: (Int) -> Unit
) {
val cities = viewModel.cities.observeAsState(listOf())
Scaffold(
topBar = { HomeAppBar() },
floatingActionButton = { HomeFab(navigateToDetailsAction) }
) {
HomeContent(cities) { id -> openCardDetailsAction(id) }
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的预览功能的代码:
@Preview
@Composable …Run Code Online (Sandbox Code Playgroud) 我有一个服务,提供大多数时间用户可见的UI.
当我遇到问题时,我正在尝试新的应用程序架构.
MyModelviewModel viewModel = ViewModelProviders.of(this).get(MyModelviewModel.class);
但正如你所知,this只能AppCompat或Fragment
还有其他选择吗?或者我可以将观察者直接放在我LiveData喜欢的东西上ViewModel
viewModel.getList().observe(Playground.this, new Observer<List<TestEntity>>() {
@Override
public void onChanged(@Nullable List<TestEntity> items) {
recyclerViewAdapter.addItems(items);
}
});
Run Code Online (Sandbox Code Playgroud) 我要离开这个 stackoverflow 答案/sf/answers/2437229581/将数据对象绑定到自定义视图。但是,在一切都设置好之后,我的视图没有被数据更新,而是TextView保持空白。这是我的代码(简化,为了适应这里)
activity_profile.xml::
<layout xmlns...>
<data>
<variable name="viewModel" type="com.example.ProfileViewModel"/>
</data>
<com.example.MyProfileCustomView
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:viewModel="@{viewModel}">
</layout>
Run Code Online (Sandbox Code Playgroud)
view_profile.xml:
<layout xmlns...>
<data>
<variable name="viewModel" type="com.example.ProfileViewModel"/>
</data>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@{viewModel.name}">
</layout>
Run Code Online (Sandbox Code Playgroud)
MyProfileCustomView.kt:
class MyProfileCustomView : FrameLayout {
constructor...
private val binding: ViewProfileBinding = ViewProfileBinding.inflate(LayoutInflater.from(context), this, true)
fun setViewModel(profileViewModel: ProfileViewModel) {
binding.viewModel = profileViewModel
}
}
Run Code Online (Sandbox Code Playgroud)
ProfileViewModel.kt:
class ProfileViewModel(application: Application) : BaseViewModel(application) {
val name = MutableLiveData<String>()
init {
profileManager.profile()
.observeOn(AndroidSchedulers.mainThread())
.subscribe(::onProfileSuccess, Timber::d)
}
fun …Run Code Online (Sandbox Code Playgroud) data-binding android android-custom-view kotlin android-viewmodel
android ×10
dagger-hilt ×2
java ×2
android-mvvm ×1
data-binding ×1
kotlin ×1
mvvm ×1
persistence ×1