简体   繁体   English

如何将数据从 Activity 传递到已创建的 Fragment?

[英]How to pass data from Activity to already created Fragment?

Lately i've been stuck, I have one Activity (not my MainActivity, I mean, it is not where I created this Fragment).最近我被卡住了,我有一个 Activity(不是我的 MainActivity,我的意思是,它不是我创建这个 Fragment 的地方)。 and I need to pass some data, I've already tried to pass using Bundle, using getter: but the same issue appears.我需要传递一些数据,我已经尝试使用 Bundle 传递,使用 getter:但出现了同样的问题。 "Attempt to invoke virtual method {...} on a null object." “尝试在 null object 上调用虚拟方法 {...}。” at the line where I call the Bundle in the Fragment, I am new at this.在我调用 Bundle in the Fragment 的那一行,我是新手。 so I'm sorry if this is a simple question and I didn't understand: Below the relevant parts of my code:所以如果这是一个简单的问题并且我不明白,我很抱歉:在我的代码的相关部分下方:

On Activity (not the main activity):在活动(不是主要活动):

public void save(){
    myGoal = spinnerGoals.getSelectedItem().toString();

    Bundle bundle = new Bundle();
    bundle.putString("goal", myGoal);
    GoalFragment goalFragment = new GoalFragment();
    goalFragment.setArguments(bundle);
}

On Fragment (where I want to put this 'goal')在片段上(我想把这个“目标”放在哪里)

private TextView goal;

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate( R.layout.fragment_goal, container, false);
    goal = view.findViewById(R.id.myGoalText);

    Bundle bundle = getArguments();
    if (bundle != null) {
        final String myGoal = bundle.getString("goal");
        goal.setText(myGoal);
    }
    return view;
}

On MainActivity (where I created the Fragments):在 MainActivity(我创建片段的地方):

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    BottomNavigationView bottomNav = findViewById(R.id.bottom_navigation);
    bottomNav.setOnNavigationItemSelectedListener(navListener);
    getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new HomeFragment() )
            .commit();
}

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_goal:
                        selectedFragment = new GoalFragment();
                        break;
                    case R.id.nav_info:
                        selectedFragment = new InfoFragment();
                        break;
                }

                getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, selectedFragment)
                        .commit();

                return true;
            }
};

Please, I've lost much time trying to solve this by myself hahaha.拜托,我已经浪费了很多时间试图自己解决这个问题哈哈哈。 If anyone can help me, i'd appreciate that!如果有人可以帮助我,我将不胜感激!

Create a method in Fragment which you want to receive data, then invoke the method in Activity.在 Fragment 中创建一个要接收数据的方法,然后在 Activity 中调用该方法。

Write this code in Activity:在Activity中写下这段代码:

 Bundle bundle = new Bundle();
 bundle.putString("goal", myGoal);
 fragmentObj.sendData(bundle);

write code in Fragment:在 Fragment 中编写代码:

public void sendData(Bundle bundle){
      String myGoal = bundle.getString("goal");
}

If the Activity(not main activity) was created from your fragment, you could use如果活动(不是主要活动)是从您的片段创建的,您可以使用

startActivityForResult()

method to receive data after the activity is ended, read about it more here活动结束后接收数据的方法,在这里阅读更多

If that is not the case, you need to persist (in storage) the data using Preferences or Room Database如果不是这种情况,您需要使用PreferencesRoom Database持久化(存储)数据

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM