Android 自定义片段不能强制转换为其他自定义片段
我试图简单地用另一个替换一个自定义片段。第一个自定义片段称为Android 自定义片段不能强制转换为其他自定义片段,android,android-fragments,Android,Android Fragments,我试图简单地用另一个替换一个自定义片段。第一个自定义片段称为menuframent,它扩展了listframent。创建活动(onCreate)时,我将其插入到我用XML定义的布局(称为layout\u container)中: FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction(); MenuFragment menufragment = new MenuFragment(); fra
menuframent
,它扩展了listframent
。创建活动(onCreate)时,我将其插入到我用XML定义的布局(称为layout\u container
)中:
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
MenuFragment menufragment = new MenuFragment();
fragmentTransaction.add(R.id.layout_container, menufragment);
fragmentTransaction.commit();
这里,我没问题
然后,当用户单击某个内容时,我想用第二个名为AlbumsFragment
(它也扩展了ListFragment
)的片段替换它。在我的onClick事件中,我将:
AlbumsFragment albumsfragment = new AlbumsFragment();
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.layout_container, albumsfragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
在这里,新片段显示良好,取代了menufragment,但同时应用程序崩溃,LogCat显示:
E/AndroidRuntime(25105): java.lang.ClassCastException: com.music.musicapp.AlbumsFragment cannot be cast to com.music.musicapp.MenuFragment
我只使用和瞄准Api级别15,所以我不使用Android支持包
编辑:
这是我的专辑片段代码,非常简单,它只是一个包含两个项目“Album1”和“Album2”的列表。我可以在点击后看到这两个项目,但应用程序立即崩溃
package com.music.musicapp;
import java.util.ArrayList;
import android.app.ListFragment;
import android.os.Bundle;
import android.widget.ArrayAdapter;
public class AlbumsFragment extends ListFragment {
// declare the array list
ArrayList<String> array = new ArrayList<String>();
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Fill up Array
array.add("album1");
array.add("album2");
setListAdapter(new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, array));
}
}
package com.music.musicapp;
导入java.util.ArrayList;
导入android.app.ListFragment;
导入android.os.Bundle;
导入android.widget.ArrayAdapter;
公共类AlbumsFragment扩展了ListFragment{
//声明数组列表
ArrayList数组=新的ArrayList();
@凌驾
已创建ActivityState上的公共无效(Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
//填充数组
数组。添加(“album1”);
数组。添加(“album2”);
setListAdapter(新的ArrayAdapter(getActivity()),
android.R.layout.simple_list_item_1,array));
}
}
问题已解决
我有另一个方法需要菜单片段
,因此,当这个片段被专辑片段
替换时,这个方法导致应用程序崩溃,因为它引用的是一个不再存在的片段
所以问题不在发布的代码中,对不起。重要的是考虑替换片段的影响,并且在引用它时要小心(检查它是否仍然在UI上,或者如果它已经被发送到后台堆栈,等等)。
感谢您的回答,很抱歉没有看到我的问题不在那里(但当项目变得复杂时,很难始终看到问题的来源:/)。问题解决了
我有另一个方法需要菜单片段
,因此,当这个片段被专辑片段
替换时,这个方法导致应用程序崩溃,因为它引用的是一个不再存在的片段
所以问题不在发布的代码中,对不起。重要的是考虑替换片段的影响,并且在引用它时要小心(检查它是否仍然在UI上,或者如果它已经被发送到后台堆栈,等等)。
感谢您的回答,很抱歉没有看到我的问题不在那里(但当项目变得复杂时,很难始终看到问题的来源:/)。我没有看到您在任何地方发布的代码中有强制转换。。。这是你代码中的其他地方吗?如果显示该片段,则该片段的代码中存在问题。发布你的专辑片段代码。我在你发布的代码中没有看到演员阵容。。。这是你代码中的其他地方吗?如果显示该片段,则该片段的代码中存在问题。发布相册片段代码。