我通过专业的Android 4.0应用开发工作我的方式。 第4章修改待办事项应用程序使用的片段,但我想测试一个姜饼设备上。 有提到在书中使用支持库,允许使用较低版本的设备上的Android V3或V4功能,但它不涉及非常好。
我与运行到一个问题,具体如下:
// Get references to the Fragments
android.app.FragmentManager fm = getFragmentManager();
ToDoListFragment todoListFragment = (ToDoListFragment) fm.findFragmentById( R.id.ToDoListFragment );
我已经得到了这些进口在顶部:进口android.support.v4.app.FragmentManager; 进口android.support.v4.app.ListFragment;
但皮棉警告对“ToDoListFragment todoListFragment =(ToDoListFragment)”行:不能从片段转换为ToDoListFragment
在我ToDoListFragment类,我有:
import android.support.v4.app.ListFragment;
public class ToDoListFragment extends ListFragment {
}
这是从书上几乎一字不差,除了改变使用的支持库。
我不是如何得到这个代码使用V4支持库正常工作明确。 我提前道歉,如果这是不足够的信息。 我仍然在学习这一点,我更熟悉C / C ++比Java。 如果我不使用的支持库,代码建立得很好,将一个冰淇淋三明治设备上运行,但我希望得到它的工作在较低水平的设备了。
您应该使用getSupportFragmentManager()
代替getFragmentManager()
android.support.v4.app.FragmentManager fm = getSupportFragmentManager()
我想做这个例子一样。 在有些情况下需要改变,使其与支持库工作的几个地方。 下面是与在评论中强调了改变我的完整的Java文件:
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();
}
}