When trying to exchange data between fragments or when passing from activity to a fragment, getArguments
always returns null
. The reason I personally do not understand.
Activation code:
FragmentManager fragmentManager; FragmentTransaction fragmentTransaction; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); fragmentManager = getSupportFragmentManager(); } public void OnClick(View view) { fragmentTransaction = fragmentManager.beginTransaction(); switch (view.getId()) { case R.id.button: { fragmentTransaction.add(R.id.container,new fragment2()); new fragment2().newInstance(10); break; } } fragmentTransaction.addToBackStack(null); fragmentTransaction.commit(); }
Fragment code:
public class fragment2 extends Fragment implements View.OnClickListener { public static fragment2 newInstance(int columnCount) { fragment2 fragment = new fragment2(); Bundle args = new Bundle(); args.putInt("ARG_COLUMN_COUNT", columnCount); fragment.setArguments(args); return fragment; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View viewFragment = inflater.inflate(R.layout.fragment2, container, false); if (getArguments() != null) { int a = getArguments().getInt("ARG_COLUMN_COUNT"); } else { Toast.makeText(getActivity(), "No getArguments", Toast.LENGTH_SHORT).show(); } return viewFragment; }
Accordingly, it always returns getArguments() == null
. Tell me why is he coming back? I did not find a clear solution anywhere. Thank.
fragment2
should not appear anywhere on the idea. The names of classes in Java are usually capitalized, like small things, and reading your code is very difficult if you publish code, respect other programmers and stick to the Java convention. - pavlofff