How to use android support library correctly

Deadly 提交于 2019-12-04 04:16:54

You should use getSupportFragmentManager() instead of getFragmentManager()

android.support.v4.app.FragmentManager fm = getSupportFragmentManager()

I wanted to do the same with this example. There are several places where alterations are required to make it work with the support library. Here's my complete java file with the changes highlighted in the comments:

package com.paad.todolist;

import java.util.ArrayList;
import android.support.v4.app.FragmentActivity; // Because we're using the support library 
                                                // version of fragments, the import has to be
                                                // FragmentActivity rather than Activity
import android.support.v4.app.FragmentManager;  // Support version of Fragment Manager
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;

// because we're using the support library version of fragments, the class has to extend the
// FragmentActivity superclass rather than the more usual Activity superclass
public class ToDoListActivity extends FragmentActivity implements NewItemFragment.OnNewItemAddedListener {

    // logging tag
    private static final String TAG = "ToDoListActivity";

    // create an array adaptor ready to bind the array to the list view
    private ArrayAdapter<String> aa;

    // set up array list to hold the ToDo items
    private ArrayList<String> todoItems;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Log.i(TAG, "The onCreate method has started");

        // inflate the view
        setContentView(R.layout.activity_to_do_list);

        // get references to the fragments

        // FragmentManager fm = getFragmentManager(); this won't work with the support library version
        FragmentManager fm = getSupportFragmentManager();   // this is the equivalent for support library

        ToDoListFragment todoListFragment = (ToDoListFragment)fm.findFragmentById(R.id.ToDoListFragment);

        // Create the array list of to do items
        todoItems = new ArrayList<String>();

        // Create the array adapter to bind the array to the listview
        aa = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, todoItems);

        // bind the array adapter to the list view
        todoListFragment.setListAdapter(aa);        
    }

    // implement the listener... It adds the received string to the array list
    // then notifies the array adapter of the dataset change
    public void onNewItemAdded(String newItem) {
        todoItems.add(newItem);
        aa.notifyDataSetChanged();
    }           
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!