我的片段类从支持v4导入正确。但是,当我在MainActivity中使用getFragmentManager时,我收到错误“无法强制转换android.app.Fragment ”。不知何故,getFragmentManager使用的是旧片段,而不是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;
}
}
我的MainActicity是这样的:**最后一行
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);
}
}
答案 0 :(得分:9)
您的片段继承自android.support.v4.app.Fragment
,因此您应该使用getSupportFragmentManager()
。如果它继承自android.app.Fragment
,则只能使用getFragmentManager()
替换
WorkoutDetailFragment frag = (WorkoutDetailFragment) getFragmentManager().findFragmentById(R.id.detail_frag);
与
WorkoutDetailFragment frag = (WorkoutDetailFragment) getSupportFragmentManager().findFragmentById(R.id.detail_frag);
答案 1 :(得分:1)
试试这段代码:
import android.support.v4.app.FragmentActivity;
public class MainActivity extends FragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WorkoutDetailFragment frag = (WorkoutDetailFragment) getSupportFragmentManager().findFragmentById(R.id.detail_frag);
frag.setWorkout(1);
}
}