MainActivity.java中运行WorkoutDetailFragment的行显示无法完成的错误。请告诉我它为什么不起作用。我从书中复制了代码。
MainActivity
package gangster.workout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WorkoutDetailFragment frag = (WorkoutDetailFragment) getFragmentManager().findFragmentById(R.id.detail_frag);
frag.setWorkout(1);
}
}
Workout.Java
package gangster.workout;
public class Workout {
private String name;
private String description;
public static final Workout[] workouts = {
new Workout("The Limb Loosener" , " Pta nhi kya ksgdrna hai isme") ,
new Workout("The Timb Loosener" , " Pta nhi kya asdfasasfasasdkrna hai isme") ,
new Workout("The Pimb Loosener" , " Pta nhi kyaasf krna hai isme") ,
new Workout("The Zimb Loosener" , " Pta nhi kyasfasa krna hai isme") ,
};
private Workout(String name , String description){
this.name = name;
this.description = description;
}
public String getDescription(){
return description;
}
public String getName(){
return name;
}
public String toString(){
return this.name;
}
}
WorkoutDetailFragment.java
package gangster.workout;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class WorkoutDetailFragment extends Fragment {
private long workoutId;
public void setWorkout(long id) {
this.workoutId = id;
}
@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 View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_workout_detail, container, false);
}
}
答案 0 :(得分:1)
使用getSupportFragmentManager()
代替getFragmentManager()