问题
I have a list in a fragment and I want a new activity to start when I press something in that list. I have only tried with my first option but when I try it I get the error:
03-20 15:16:13.017: E/AndroidRuntime(941): Caused by: java.lang.ClassCastException: com.test.test.Algebra cannot be cast to android.app.Activity
Here's my fragment class:
public class FragmentTest extends SherlockListFragment {
String formler[]= {
"Algebra",
"Aritmetik",
"Differential- och integralkalkyl",
"Funktioner",
"Geometri",
"Komplexa tal",
"Statistik och sannolikhet",
"Trigonometri"
};
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
setListAdapter(new ArrayAdapter<String>(getActivity().getBaseContext(), android.R.layout.simple_list_item_1, formler));
return super.onCreateView(inflater, container, savedInstanceState);
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
String choice = formler[position];
try{
@SuppressWarnings("rawtypes")
Class choiceClass = Class.forName("com.test.test." + choice);
Intent startIntent = new Intent(getActivity().getBaseContext(), choiceClass);
startActivity(startIntent);
}catch(ClassNotFoundException e){
e.printStackTrace();
}
}
}
What am I doing wrong?
回答1:
Make sure that Algebra is extending an activity and also you can simple initiate an activity like this new Intent(currectActivity.this, Algebra.class);
回答2:
I never used a SherlockListFragment, but I used a Fragment. When I wanted to initialize a new fragment, I used
NewFragmentClass newFragment = new NewFragmentClass ();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.myCurrentFragmentId, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
I Hope this help
来源:https://stackoverflow.com/questions/15527850/classcastexception-cannot-be-cast-to-android-app-activity