[英]How to pass data from Activity to already created Fragment?
最近我被卡住了,我有一個 Activity(不是我的 MainActivity,我的意思是,它不是我創建這個 Fragment 的地方)。 我需要傳遞一些數據,我已經嘗試使用 Bundle 傳遞,使用 getter:但出現了同樣的問題。 “嘗試在 null object 上調用虛擬方法 {...}。” 在我調用 Bundle in the Fragment 的那一行,我是新手。 所以如果這是一個簡單的問題並且我不明白,我很抱歉:在我的代碼的相關部分下方:
在活動(不是主要活動):
public void save(){
myGoal = spinnerGoals.getSelectedItem().toString();
Bundle bundle = new Bundle();
bundle.putString("goal", myGoal);
GoalFragment goalFragment = new GoalFragment();
goalFragment.setArguments(bundle);
}
在片段上(我想把這個“目標”放在哪里)
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;
}
在 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;
}
};
拜托,我已經浪費了很多時間試圖自己解決這個問題哈哈哈。 如果有人可以幫助我,我將不勝感激!
在 Fragment 中創建一個要接收數據的方法,然后在 Activity 中調用該方法。
在Activity中寫下這段代碼:
Bundle bundle = new Bundle();
bundle.putString("goal", myGoal);
fragmentObj.sendData(bundle);
在 Fragment 中編寫代碼:
public void sendData(Bundle bundle){
String myGoal = bundle.getString("goal");
}
如果活動(不是主要活動)是從您的片段創建的,您可以使用
startActivityForResult()
活動結束后接收數據的方法,在這里閱讀更多
如果不是這種情況,您需要使用Preferences
或Room Database
持久化(存儲)數據
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.