[英]Pass data between fragments with Bundle
我閱讀了很多有關此內容的討論,有人建議使用Bundle在同一活動中的兩個片段之間傳遞數據...我嘗試了一些操作,但是沒有用。 我的GroupDetailActivity
有2個片段。 PaymentFragment從數據庫下載數據並將其顯示在listView中,片段FragmentReport
則顯示付款報告。 因此,在paymentFragment獲取數據之后,我需要將其中一些傳遞給第二個片段。 那是我的代碼:
PaymentFragment:
final Bundle bundle = new Bundle();
final FragmentReport fragment = new FragmentReport();
// This is inside the onCreateView, where I get the the data from the db and show them in a listview
bundle.putInt("num_of_pay", cont);
Log.v("cont", String.valueOf(cont)); // it display the correct number of person
fragment.setArguments(bundle);
getFragmentManager().beginTransaction().replace(R.id.container, fragment);
然后,在我的FragmentReport中,在OnCreateView
:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView=inflater.inflate(R.layout.report_fragment,container,false);
numberOfPaymentTV = rootView.findViewById(R.id.n_payment_tv);
Bundle args = this.getArguments();
if (args != null){
numberOfPaymentTV.setText(args.getInt("num_of_pay"));
Log.v("totalPayment", String.valueOf(args.getInt("num_of_pay"))); // I don't get any log, maybe this fragment doesn't receive the data
}
return rootView;
}
}
我沒有收到任何錯誤,但是textView沒有顯示“ cont”值。 也許我可以使用sharedPreferences? 可以通過Bundle實現嗎?
您可以在onCreate()
函數中獲取args。
private Bundle bundle;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_blank, container, false);
((TextView) view.findViewById(R.id.textView))
.setText(String.valueOf(bundle.getInt("KEY")));
return view;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.bundle = getArguments();
}
在TextView中將int設置為文本時,應使用String.valueOf(int):
numberOfPaymentTV.setText(String.valueOf(getArguments().getInt("num_of_pay"))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.