2013-12-05 7 views
0

Я новичок в фрагментах и ​​отлаживаю пример из «Профессиональной разработки приложений для Android 4». Глава 4, я думаю. Я пробовал код прямо из книги, которая не использует библиотеку поддержки и библиотеку поддержки, но я все равно получаю такое же исключение ClassCastException.ClassCastException: Фрагмент не может быть передан в ListFragment

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

Изменения в

<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> 
+0

Facepalm. Я буквально смотрел на это целыми днями. Я даже перепроверял что-то простое, прежде чем представить это. Спасибо! –

Смежные вопросы