如何在底部导航片段(或导航抽屉)之间传递数据?

huangapple go评论78阅读模式
英文:

How to pass data between Bottom Navigation fragments (or Navigation Drawer)?

问题

以下是翻译好的内容:

我有一个情况,我在Android开发方面不够好,无法实现在底部导航目标之间传递数据的方法。

我需要从CreateFragment获取EditText中的文本,传递到RecipesFragment,在那里我将在数据库中添加一个新项目,RecyclerView将根据此数据进行更新(我正在使用LiveData + MVVM)。

【我的底部导航栏】1

所以,我正在寻找一种方法。我找不到任何适当/具体的解释,我认为在底部导航或导航抽屉中在片段之间传递数据是重要的功能,但对于像我这样的初学者来说可能很难 :(。

附加信息:在我的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);

        // 当设备旋转时保持当前片段打开
        if (savedInstanceState == null) {

            // 设置NavigationView中的默认选定项
            bottomNavigationView.setSelectedItemId(R.id.nav_home);
        }
    }

    // 根据NavigationView中选定的项处理视图切换
    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() { // 在点击浮动按钮时触发
    String title = edit_title.getText().toString();
    String ingredients = edit_ingredients.getText().toString();

    if (title.trim().isEmpty() || ingredients.trim().isEmpty()) {
        Toast.makeText(getActivity(), "请插入标题和描述", Toast.LENGTH_SHORT).show();
        return;
    }

    // 这里应该将数据传递给RecipesFragment中的RecyclerView
    // TODO

    //
}

RecipesFragment.java

public void getRecipeFromCreateFragment() {

    // 这里应该从Create Activity传递数据
    // TODO



    //

    Recipe recipe =
            new Recipe("hh", "title", "ingredients", "instructions", "ss", "image");
    recipeViewModel.insert(recipe);

    Toast.makeText(getActivity(), "已保存食谱", Toast.LENGTH_SHORT).show();
}
英文:

I have a situation, I´m not good enough in android dev to implement a way to pass data between Bottom Navigation destinations.

I would need to get text from EditText from CreateFragment to a RecipesFragment, where I would add a new item in the database and the RecyclerView would update (I´m using LiveData + MVVM) based on this data.

My Bottom Navigation Bar

So, I´m asking for a way. I couldn´t find any proper/specific explanation and I think that passing data between fragments in Bottom Navigation or Navigation Drawer is important feauture but hard i guess for beginners like me :(.

Additional info: I host a FrameLayout(id-fragment_container) in my MainActivity in what I change fragments based on location in Bottom Nav selected. (check code)

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
//
}

RecipesFragment.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();
}

答案1

得分: 1

UPDATE: 好的,我从一位 Reddit 用户那里得到了帮助,解决方案非常简单,我甚至不应该考虑在我的情况下在片段之间传递数据。

解决方案是通过 ViewModel 在 CreateFragment 中将食谱简单地添加到数据库中,真的没有必要将数据传递给 RecipesFragment,然后在那里添加。

然而,如果有人知道在导航视图(导航抽屉)中在片段之间传递数据的更好、更推荐的方法,对于将来会非常有帮助。

谢谢。

英文:

UPDATE: Okay, I got help from a fellow redditer and the solution was really easy and I shouldn´t had even thought about passing data between fragments in my case.

The solution is to simply add the recipe to the database via ViewModel in the CreateFragment, there´s really no need to pass the data to the RecipesFragment and then add it there.

HOWEVER, if someone know a better, more recommended way to pass data between fragments in Navigation View (Navigation Drawer) it would be really helpful for the future.

Thanks.

huangapple
  • 本文由 发表于 2020年6月5日 22:30:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/62217714.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定