如何解决MainActivity无法强制转换为Interface
我正在尝试使用接口在片段之间共享变量。我的问题是出现此错误:java.lang.ClassCastException: com.example.application.activities.MainActivity cannot be cast to com.example.application.ListGeneratedInterface
这是我片段的一部分:
public class MealsFragment extends Fragment {
View view;
EditText numberText;
public ListMealsInterface listMealsInterface;
public ListGeneratedInterface listGeneratedInterface;
ArrayList<Meal> listMeals = new ArrayList<Meal>();
ArrayList<Meal> generatedList = new ArrayList<Meal>();
private static final String PREFS = "PREFS";
SharedPreferences sharedPreferences;
@Override
public View onCreateView (LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState) {
view = inflater.inflate(R.layout.meals_fragment,container,false);
numberText = (EditText) view.findViewById(R.id.number_meals);
listMealsInterface = (ListMealsInterface)getContext();
listMeals = listMealsInterface.getList();
//The error comes from here
listGeneratedInterface = (ListGeneratedInterface)getContext();
generatedList = listGeneratedInterface.getListGenerated();
Button generateButton = view.findViewById(R.id.generate_list_button);
generateButton.setOnClickListener( new View.OnClickListener() {
@Override
public void onClick(View v) {
if(getNumberMeals() <= maxSavedMeals() ) {
closeKeyboard(view);
saveNumberInSP();
resetIsPresent();
loadFragment(new ListGeneratedFragment());
}
else {
Toast.makeText(getContext(),getString(R.string.number_meals_over_limit),Toast.LENGTH_SHORT);
}
}
});
loadFragment(new ListGeneratedFragment());
return view;
}
}
这是界面:
package com.example.application;
import java.util.ArrayList;
public interface ListGeneratedInterface {
public ArrayList<Meal> getListGenerated();
}
在另一个要创建变量的片段中将其覆盖,该片段仅返回该变量。
我希望有人能帮助我,我不知道要解决我的问题...
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。