我目前在同一活动中托管了两个片段。我想将字符串变量从片段1传递到片段2。我尝试使用bundle,但仅获得空值。
片段1代码:
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.customer_one,container,false);
edemail = v.findViewById(R.id.ed_email);
btn = v.findViewById(R.id.btn_next);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
email = edemail.getText().toString().trim();
Customer_Frag2 cf2 = new Customer_Frag2();
Bundle data = new Bundle();
data.putString("Email",email);
cf2.setArguments(data);
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.layout_one,cf2);
ft.addToBackStack(null);
ft.commit();
}
});
return v;
}
片段2代码:
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.customer_two,container,false);
tc = v.findViewById(R.id.txt);
Bundle args = getArguments();
if(args != null){
String myvalue = args.getString("Email");
tc.setText(myvalue);
}
return v;
}
除了使用bundle,我还尝试使用interface,但是无法从片段1获取字符串。
答案 0 :(得分:0)
在fragment2中执行以下操作:
private String myvalue = "";
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle args = getArguments();
if(args != null){
myvalue = args.getString("Email");
}
}
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.customer_two,container,false);
tc = v.findViewById(R.id.txt);
tc.setText(myvalue);
return v;
}
希望这会对您有所帮助。