[英]How to pass string variable between fragments in navigation drawer activity template
[英]How to pass data between Bottom Navigation fragments (or Navigation Drawer)?
我有一種情況,我在 android 開發中還不夠好,無法實現在底部導航目的地之間傳遞數據的方法。
我需要從 CreateFragment 中的 EditText 獲取文本到一個 RecipesFragment,我將在數據庫中添加一個新項目,並且 RecyclerView 將根據這些數據更新(我正在使用 LiveData + MVVM)。
所以,我正在尋求一種方法。 我找不到任何正確/具體的解釋,我認為在底部導航或導航抽屜中的片段之間傳遞數據是重要的功能,但我想對於像我這樣的初學者來說很難:(。
附加信息:我在我的 MainActivity 中托管一個 FrameLayout(id-fragment_container),我根據所選底部導航中的位置更改片段。 (檢查代碼)
MainActivity.java
public class MainActivity extends AppCompatActivity {
private BottomNavigationView bottomNavigationView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bottomNavigationView = findViewById(R.id.bottom_navigation);
bottomNavigationView.setOnNavigationItemSelectedListener(navListener);
// Keeps the current fragment opened when the device rotates
if (savedInstanceState == null) {
// Sets the default selected item in NavigationView
bottomNavigationView.setSelectedItemId(R.id.nav_home);
}
}
// Handles switching the view based on NavigationView item selected
private BottomNavigationView.OnNavigationItemSelectedListener navListener =
new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
Fragment selectedFragment = null;
switch (item.getItemId()) {
case R.id.nav_home:
selectedFragment = new HomeFragment();
break;
case R.id.nav_recipes:
selectedFragment = new RecipesFragment();
break;
case R.id.nav_create:
selectedFragment = new CreateFragment();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
selectedFragment).commit();
return true;
}
};
CreateFragment.java
private void saveRecipe() { //trigered on floating button press
String title = edit_title.getText().toString();
String ingredients = edit_ingredients.getText().toString();
if (title.trim().isEmpty() || ingredients.trim().isEmpty()) {
Toast.makeText(getActivity(), "Please insert a title and description", Toast.LENGTH_SHORT).show();
return;
}
// THIS SHOULD PASS DATA TO RecipesFragment INTO RECYCLERVIEW
// TODO
//
}
食譜Fragment.java
public void getRecipeFromCreateFragment() {
// THERE SHOULD BE PASSED DATA FROM CREATE ACTIVITY
// TODO
//
Recipe recipe =
new Recipe("hh", "title", "ingredients", "instructions", "ss", "image");
recipeViewModel.insert(recipe);
Toast.makeText(getActivity(), "Recipe saved", Toast.LENGTH_SHORT).show();
}
更新:好的,我得到了一位 redditer 同事的幫助,解決方案非常簡單,在我的案例中,我什至不應該考慮在片段之間傳遞數據。
解決方案是通過 CreateFragment 中的 ViewModel 將配方簡單地添加到數據庫中,實際上不需要將數據傳遞給 RecipesFragment 然后將其添加到那里。
但是,如果有人知道一種更好、更推薦的方式在導航視圖(導航抽屜)中的片段之間傳遞數據,那么這對未來非常有幫助。
謝謝。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.