我的fragment类从support v4中正确导入。然而,当我在MainActivity中使用getFragmentManager时,出现错误"cannot cast android.app.Fragment"。不知何故,getFragmentManager正在使用旧的fragment,而不是supprt.v4.app.Fragment。你知道应该使用哪个方法吗?
package example.hfad.fragments_chapter7;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class WorkoutDetailFragment extends Fragment {
private long workoutId;
public WorkoutDetailFragment() {
// Required empty public constructor
}
@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);
}
public void setWorkout(long id){
this.workoutId = id;
}
}
我的MainActivity是这样的:**最后一行
gerFragmentManager().findFragmentById
抱怨说我无法将android.app.Fragment强制转换为上面定义的自定义片段类。**
package example.hfad.fragments_chapter7;
import android.app.Activity;
import android.os.Bundle;
public class MainActivity extends Activity {
@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);
}
}
AppCompatActivity
代替FragmentActivity
,并且由于你正在使用v4支持库的fragment,因此你必须使用getSupportFragmentManager()
来执行你的fragment操作。 - Shadab Ansari