如何在MainActivity和Fragment之间发送参数?
我已经尝试过使用getSupportFragmentManager方法来完成它,但它没有工作
重要方法代码
MainActivity.java
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(savedInstanceState != null){
getSupportFragmentManager().beginTransaction()
.add(R.id.frag_text, createCustomFragment()).commit();
}
}
TesteFragment.java
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_teste, container, false);
Bundle bundle = getArguments();
EditText text = (EditText) getActivity().findViewById(R.id.et_text);
EditText size = (EditText) view.findViewById(R.id.et_size);
TextView fragText = (TextView) view.findViewById(R.id.frag_text);
Button changeButton = (Button) view.findViewById(R.id.bt_change);
return view;
}
FragmentTeste.java中的变量状态
为什么在我从MainActivity传递参数时bundle是null?
感谢
答案 0 :(得分:0)
您的createCustomFragment()
功能有什么作用?
尝试做这样的事情:
Bundle data = new Bundle();
data.putString("name",value);
Fragment fragment = new MyFragment();
fragment.setArguments(data);
答案 1 :(得分:0)
我的createCustomFragment方法具有此范围
private TesteFragment createCustomFragment(){
Bundle bundle = new Bundle();
bundle.putString("nome", "Joao");
TesteFragment testeFragment = new TesteFragment();
testeFragment.setArguments(bundle);
return testeFragment;
}