[英]How to get value from one fragment and pass to another fragment
我有兩個片段,一個是片段X和片段y。片段X用於使用Web服務的注冊過程。 我想將相同的值從Fragment X傳遞給FragmentY。
這是我的代碼:
片段x:
Signup.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String sName = Name.getText().toString(); String sPhoneNo = Phone.getText().toString(); String sEmailId = EmailId.getText().toString(); // Instantiate Http Request Param Object RequestParams params = new RequestParams(); if (Utility.isNotNull(sName) && Utility.isNotNull(sPhoneNo) && Utility.isNotNull(sEmailId) ) { if (Utility.line2_validate(sName)) { if (Utility.validate(sPhoneNo)) { if (Utility.email_validate(sEmailId)) { //Get value from this Fragment FragmentY pf = new FragmentY (); Bundle args = new Bundle(); args.putString("mobile", sPhoneNo); args.putString("email",sEmailId); pf.setArguments(args); //Inflate the fragment getFragmentManager().beginTransaction().add(R.id.passwordLayout, pf).commit(); // Put Http parameter username with value of Name Edit View control params.put("name", sName); // Put Http parameter email with value of Email Edit Value control params.put("email", sEmailId); // Put Http parameter mobile with value of Mobile Edit Value control params.put("mobile", sPhoneNo); // Invoke Signup RESTful Web Service with Http parameters signUpWS(params); //Toast.makeText(getActivity().getApplicationContext(), "Success", Toast.LENGTH_SHORT).show(); //((MainActivity) getActivity()).navigatetoPasswordActivity(); } else { EmailId.setError("Enter valid Email"); } } else { Phone.setError("Enter valid Mobile"); } } else { Name.setError("Enter valid Name"); } } else { Toast.makeText(getActivity().getApplicationContext(), "Please fill the form, don't leave any field blank", Toast.LENGTH_SHORT).show(); } } });
片段Y:
// Retrive the value from fragment x String strMobile = getArguments().getString("mobile"); String strEmail = getArguments().getString("email");
請任何人幫助我..
提前致謝!
您可以通過在片段中創建構造函數來將值傳遞給Farf
例如,
對於片段x在構造函數中傳遞值
PasswordFragment pf = new PasswordFragment (name, email, mobile);
對於fragmnet y,您可以從此構造函數中檢索值
String name, email, mobile
public PasswordFragment(String name, String email, String mobile) {
// TODO Auto-generated constructor stub
this.name=name;
this.email=email;
this.mobile=mobile;
}
我知道Fragment應該通過它們所附加的Activity進行通信; 解決您的問題的一種方法是聲明
final Activity activity = this.getActivity();
並使用它通過Activity屬性(您可以選擇私有或公共)來傳遞所需的值,例如
String value1;
String value2; //Into Activity
這樣一來,您就可以從FragmentY中檢索它們的值。
編輯:當然,在您的Fragment中聲明最終的Activity對象時,您將需要強制轉換為YourCustomActivity。
我建議您對此進行調查。 http://developer.android.com/training/basics/fragments/communicating.html
它非常干凈和可取。任何片段都不應該直接進行通信。最好的方法是使用調用活動作為兩個片段之間的中介
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.