ClassCastException:Fragment无法强制转换为ListFragment

时间:2013-12-05 15:38:34

标签: android android-fragments classcastexception

我认为,我是初学者并且正在尝试“专业Android 4应用程序开发”第4章中的示例。我直接尝试了不使用支持库和支持库的书中的代码,但我仍然得到相同的ClassCastException。

ToDoListActivity.java

package com.example.todolist4;

import java.util.ArrayList;

import android.support.v4.app.FragmentManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.widget.ArrayAdapter;

public class ToDoListActivity extends FragmentActivity implements NewItemFragment.OnNewItemAddedListener {

private ArrayAdapter<String> aa;
private ArrayList<String> todoItems;

public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);

    //Inflate you view
    setContentView(R.layout.main);

    // Get references to the Fragments
    FragmentManager fm = getSupportFragmentManager();
    ToDoListFragment todoListFragment = (ToDoListFragment)    fm.findFragmentById(R.id.TodoListFragment);

    // Create the array list of todo 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 listview.
    todoListFragment.setListAdapter(aa);
}

public void onNewItemAdded(String newItem){
    todoItems.add(newItem);
    aa.notifyDataSetChanged();
}

}

NewItemFragment.java

package com.example.todolist4;

import android.app.Activity;
import android.support.v4.app.Fragment;
import android.view.KeyEvent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;


public class NewItemFragment extends Fragment {

private OnNewItemAddedListener onNewItemAddedListener;

public interface OnNewItemAddedListener {
    public void onNewItemAdded(String newItem);
}

@Override
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();
                    myEditText.setText("");
                    return true;
                }
            return false;
        }
    });

    return view;
}

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);

    try{
        onNewItemAddedListener = (OnNewItemAddedListener)activity;
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString() + " must implement  OnNewItemAddedListener" );
        }
    }
}

ToDoListFragment.java

package com.example.todolist4;

import android.support.v4.app.ListFragment;

public class ToDoListFragment extends ListFragment {

}

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.todolist4.NewItemFragment"
        android:id="@+id/NewItemFragment"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        />
    <fragment android:name="com.example.todolist4.NewItemFragment"
        android:id="@+id/TodoListFragment"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        />
</LinearLayout>

new_item_fragment.xml

<?xml version="1.0" encoding="utf-8"?>

<EditText xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/myEditText"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="@string/addItemHint"
    android:contentDescription="@string/addItemContentDescription"/>

logcat的

Caused by: java.lang.ClassCastException: com.example.todolist4.NewItemFragment cannot be cast to com.example.todolist4.ToDoListFragment
            at com.example.todolist4.ToDoListActivity.onCreate(ToDoListActivity.java:23)
            at android.app.Activity.performCreate(Activity.java:5104)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
            at android.app.ActivityThread.access$600(ActivityThread.java:141)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:5041)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
            at dalvik.system.NativeStart.main(Native Method)

此行正在抛出异常

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

有什么建议吗?

1 个答案:

答案 0 :(得分:1)

更改为

<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.todolist4.NewItemFragment"
        android:id="@+id/NewItemFragment"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        />
    <fragment android:name="com.example.todolist4.ToDoListFragment" //change here
        android:id="@+id/TodoListFragment"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        />
</LinearLayout>