Fragment的代码:
public class NewItemFragment extends Fragment
{
private OnNewItemAddedListener onNewItemAddedListener;
public interface OnNewItemAddedListener
{
public void onNewItemAdded(String newItem);
}
public void onAttach(Activity activity)
{
super.onAttach(activity);
try
{
onNewItemAddedListener=(OnNewItemAddedListener)activity;
}
catch(ClassCastException e)
{
throw new ClassCastException(activity.toString()+"must implement OnNewItemAddedListener");
}
}
public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.new_item_fragment, container,false);
final EditText myEditText = (EditText)view.findViewById(R.id.myEditText);
myEditText.setOnKeyListener(new View.OnKeyListener(){
public boolean onKey(View v,int keyCode,KeyEvent event){
if(event.getAction()==KeyEvent.ACTION_DOWN)
if((keyCode == KeyEvent.KEYCODE_DPAD_CENTER)||
(keyCode == KeyEvent.KEYCODE_ENTER)){
String newItem = myEditText.getText().toString();
onNewItemAddedListener.onNewItemAdded(newItem);
myEditText.setText("");
return true;
}
return false;
}
});
return view;
}
}
main.xml的代码:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment android:name="com.example.dolist.NewItemFragment"
android:id="@+id/NewItemFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
<fragment android:name="com.example.dolist.ToDoListFragment"
android:id="@+id/TodoListFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
ToDolistActivity的代码:
public class ToDoListActivity extends FragmentActivity {
private ArrayAdapter<String> aa;
private ArrayList<String> todoItems;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
FragmentManager fm = getFragmentManager();
ToDoListFragment todoListFragment = (ToDoListFragment)fm.findFragmentById(R.id.TodoListFragment);
todoItems = new ArrayList<String>();
aa = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,todoItems);
todoListFragment.setListAdapter(aa);
}
}
就在ToDListActivity中ToDoListFragment todoListFragment = (ToDoListFragment)fm.findFragmentById(R.id.TodoListFragment);
会报出Cannot cast from Fragment to ToDoListFragment的错误
新手,只是照书上打的,实在没看明白哪里错了?这个地方不可转换吗???