Android Fragment getArguments() returns null

后端 未结 4 379

As the title suggest.
I\'ve downloaded Fragment code from here, http://developer.android.com/shareables/training/FragmentBasics.zip.
It is Fragment exam

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-06 11:46

    @tonny

    I've download the FragmentBasics.zip. I only change the argument name. Here is the code and result pic.

    MainActivity

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.news_articles);
    
        // Check whether the activity is using the layout version with
        // the fragment_container FrameLayout. If so, we must add the first fragment
        if (findViewById(R.id.fragment_container) != null) {
    
            // However, if we're being restored from a previous state,
            // then we don't need to do anything and should return or else
            // we could end up with overlapping fragments.
            if (savedInstanceState != null) {
                return;
            }
    
            // Create an instance of ExampleFragment
            HeadlinesFragment fragment = new HeadlinesFragment();
    
            // In case this activity was started with special instructions from an Intent,
            // pass the Intent's extras to the fragment as arguments
    //            firstFragment.setArguments(getIntent().getExtras());
            //test
            Bundle args= new Bundle();
            args.putString("category", "clothes");
            args.putString("item", "shirts");
            fragment.setArguments(args);
    
            // Add the fragment to the 'fragment_container' FrameLayout
            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.fragment_container, fragment).commit();
        }
    }
    

    HeadlinesFragment

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    
        // We need to use a different list item layout for devices older than Honeycomb
        int layout = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ?
                android.R.layout.simple_list_item_activated_1 : android.R.layout.simple_list_item_1;
    
        Bundle args = getArguments();
        if (args == null) {
            Toast.makeText(getActivity(), "arguments is null " , Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(getActivity(), "text " + args , Toast.LENGTH_LONG).show();
        }    
    
        // Create an array adapter for the list view, using the Ipsum headlines array
        setListAdapter(new ArrayAdapter(getActivity(), layout, Ipsum.Headlines));
    }
    

    here is the result

    enter image description here

提交回复
热议问题