Activity代碼
String phone = ((EditText) findViewById(R.id.phone))
.getText().toString();
if (phone.isEmpty()) {
Toast.makeText(ForgetPsdActivity.this, "請輸入手機號碼",
Toast.LENGTH_LONG).show();
break;
} else {
ForgetPSD2Fragment fragment2 = new ForgetPSD2Fragment();
transaction.replace(R.id.fragmentcontainer, fragment2);
fragment2.setViewPhone(phone);
transaction.addToBackStack(null);
step = 2;
}
fragment2代碼
public class ForgetPSD2Fragment extends Fragment {
private View view;
private TextView txtPhone;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.forgetpsd2, container, false);
txtPhone = (TextView) view.findViewById(R.id.txtphone);
return view;
}
public void setViewPhone(String phone) {
if (txtPhone == null) {
Log.i("debug", phone + "abs");
}else{
txtPhone.setText(phone);
}
}
}
上邊是我寫的在Activity與fragment之間通信的例子,但是測試發現在調用fragment2.setViewPhone(phone);的時候,txtPhone為null值,請教一下是為什麼,有什麼解決辦法可以處理這個問題?
fragment2.setViewPhone(phone);//這時候還沒初始化
用
Bundle bundle = new Bundle();
bundle.putString("order", "1111");
fragment.setArguments(bundle);
然後在fragment中
String name = getArguments().getString("order");