我希望從另一個活動(RemoveStatement)訪問活動方法(Budgeting.readFromDb())。 RemoveStatement貫穿了BudgetingFragment(預算內的佔位符片段)的意圖。但是,當我嘗試獲取BudgetingFragment的一個實例(通過getFragmentManager()。findFragmentByTag(「budgetingFragment」))來調用getActivity()時,它返回一個空對象。我似乎無法弄清楚爲什麼這樣做以及如何解決這個問題。內budgetingFragment更換片段後Android:從另一個Activity獲取碎片活動實例
- 添加標籤堆棧中
- 呼叫getSupportFragmentManager()executePendingTransactions():
我曾嘗試下面的東西。
任何幫助解決這個問題將不勝感激。預算之內
方法來改變片段
public void onClickFragment(int id, String arrowDirection){
//Get current Fragment
Fragment currentFragment = getSupportFragmentManager().findFragmentById(R.id.budgetingFragment);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
if (currentFragment instanceof BudgetingOverviewFragment && arrowDirection == "Left"){
IncomeFragment incomeFragment = new IncomeFragment();
transaction.replace(R.id.budgetingFragment, incomeFragment, "budgetingFragment");
}
else if (currentFragment instanceof BudgetingOverviewFragment && arrowDirection == "Right"){
ExpenseFragment expenseFragment = new ExpenseFragment();
transaction.replace(R.id.budgetingFragment, expenseFragment, "budgetingFragment");
}
else if (currentFragment instanceof IncomeFragment && arrowDirection == "Right"){
BudgetingOverviewFragment overviewFragment = new BudgetingOverviewFragment();
transaction.replace(R.id.budgetingFragment, overviewFragment, "budgetingFragment");
}
else{
BudgetingOverviewFragment overviewFragment = new BudgetingOverviewFragment();
transaction.replace(R.id.budgetingFragment, overviewFragment, "budgetingFragment");
}
transaction.addToBackStack("budgetingFragment");
transaction.commit();
getSupportFragmentManager().executePendingTransactions();
}
代碼中RemoveStatements onCreate()方法:
FragmentManager fm = getFragmentManager();
//This Fragment is a null pointer
Fragment callingFragment = fm.findFragmentByTag("budgetingFragment");
//This crashes the application as getActivity() is called on a null reference
Budgeting budgeting = (Budgeting) callingFragment.getActivity();
那麼獲得片段實例甚至預算活動實例的最佳方法是什麼?建議將預算活動片段管理器的實例傳遞給RemoveStatement – JoeScott1232
片段不應該意識到彼此(鬆耦合)。在主機Activity中爲參數設置片段並使用[callbacks](http://developer.android.com/training/basics/fragments/communicating.html) –