[英]Send data to one activity's fragment from another activity?
I have MainActivity which contains TabLayout with tabs: each tab is a fragment and each one has a RecyclerView. 我有MainActivity,其中包含带有选项卡的TabLayout:每个选项卡都是一个片段,每个选项卡都有RecyclerView。 When I tap FAB in Main Activity, NewReminderActivity is opened. 当我在主活动中点击FAB时,NewReminderActivity被打开。
I use Architecture Components: Entity(Reminder), DAO, Room, ViewModel, LiveData and Repository. 我使用架构组件:实体(提醒),DAO,Room,ViewModel,LiveData和存储库。
The question is: 问题是:
I have some ideas, but could you help me please and give me a right direction for implementing: 我有一些想法,但是请您帮我,给我正确的实施方向:
1) I guess, I should deliver data to MainActivity, then from MainActivity to the fragment and use ViewModel as mentioned in https://developer.android.com/topic/libraries/architecture/viewmodel.html#sharing , am I right? 1)我想,我应该先将数据传递给MainActivity,然后再从MainActivity传递至片段,并按照https://developer.android.com/topic/libraries/architecture/viewmodel.html#sharing中所述使用ViewModel,对吗?
2) I guess I should use setResult() in NewReminderActivity, am I right? 2)我猜我应该在NewReminderActivity中使用setResult(),对吗?
If you are using Room, there is no reason for you to use setResult
to transfer new item to any of these previous Fragments/Activities, because Room manages invalidation automatically. 如果您使用的是Room,则无需使用setResult
将新项目转移到这些以前的“片段/活动”中的任何一个,因为Room会自动管理无效。
@Dao
public interface MyDao {
@Query("SELECT * FROM ITEM")
LiveData<List<Item>> getItemsWithChanges();
@Insert(onConflict = OnConflictStrategy.REPLACE)
void insertItem(Item item);
}
Then 然后
public class MyViewModel extends ViewModel {
private final LiveData<List<Item>> items;
public LiveData<List<Item>> getItems() {
return items;
}
public MyViewModel(MyDao myDao) {
items = myDao.getItemsWithChanges();
}
}
Then 然后
public class MyFragment extends Fragment {
MyViewModel myViewModel;
@Override
protected void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
myViewModel = ViewModelProviders.of(getActivity(), viewModelFactory).get(MyViewModel.class);
myViewModel.getItems().observe(getViewLifecycleOwner(), (items) -> {
if(items != null) {
adapter.submitList(items);
}
});
}
}
In which case all you need to do in your second Activity is insert the new item, then finish out: 在这种情况下,您需要在第二个活动中要做的就是插入新项,然后完成:
// imagine this is on background thread
myDao.insertItem(item);
runOnUiThread(() -> {
finish();
});
And all your RecyclerViews will update with the new item (if they are part of the results as the condition matches it). 并且您的所有RecyclerViews都将使用新项进行更新(如果条件匹配,它们将成为结果的一部分)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.