我收到了一个奇怪的错误。在我的代码中,我试图将WorkoutDetailFragment强制转换为WorkoutDetailFragment类型的对象。以下是WorkoutDetailFragment的代码:
package com.hfad.workout;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.Fragment;
public class WorkoutDetailFragment extends Fragment {
private long workoutId;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
if(savedInstanceState != null)
{
workoutId = savedInstanceState.getLong("workoutId");
}
android.support.v4.app.FragmentTransaction ft = getChildFragmentManager().beginTransaction();
com.hfad.workout.StopwatchFragment stopwatchFragment = new com.hfad.workout.StopwatchFragment();
ft.replace(R.id.stopwatch_container, stopwatchFragment);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
return inflater.inflate(R.layout.fragment_workout_detail, container, false);
}
@Override
public void onStart(){
super.onStart();
View view = getView();
if(view != null)
{
TextView title = (TextView) view.findViewById(R.id.textTitle);
Workout workout = Workout.workouts[(int) workoutId];
title.setText(workout.getName());
TextView description = (TextView) view.findViewById(R.id.textDescription);
description.setText(workout.getDescription());
}
}
@Override
public void onSaveInstanceState(Bundle savedInstanceState)
{
savedInstanceState.putLong("workoutId", workoutId);
}
public void setWorkout(long id)
{
this.workoutId = id;
}
}
此类名为DetailActivity的错误发生在:" Inconvertable类型;无法投射' android.app.Fragment' to' com.hfad.workout.WorkoutDetailFragment'。这是DetailActivity的代码,我在有错误的代码片段顶部发表评论:
package com.hfad.workout;
import android.app.Activity;
import android.os.Bundle;
public class DetailActivity extends Activity
{
public static final String EXTRA_WORKOUT_ID = "id";
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
//This is where the error occurs:
WorkoutDetailFragment workoutDetailFragment = (WorkoutDetailFragment) getFragmentManager().findFragmentById(R.id.detail_frag);
int workoutId = (int) getIntent().getExtras().get(EXTRA_WORKOUT_ID);
workoutDetailFragment.setWorkout(workoutId);
}
}
非常感谢任何帮助,如果需要任何其他代码或进一步说明,请告诉我们。)
答案 0 :(得分:2)
如果您使用支持ActivityCompat,则需要使用Fragment而不是普通的旧活动。常规Activity对支持片段一无所知,并且它们不共享任何共同的祖先 - 只是符合相同的接口(不是实际的Interface
)。