我阅读了很多关于此的讨论,有人建议使用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实现吗?
答案 0 :(得分:0)
您可以在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();
}
答案 1 :(得分:0)
当在TextView中将int设置为文本时,应使用String.valueOf(int):
numberOfPaymentTV.setText(String.valueOf(getArguments().getInt("num_of_pay"))