对照代码:
class MyFragmentPagerAdapter extends FragmentPagerAdapter{ public MyFragmentPagerAdapter(FragmentManager fm) { super(fm); // TODO Auto-generated constructor stub } @Override public Fragment getItem(int arg0) { // TODO Auto-generated method stub Fragment ft = null; switch (arg0) { case 0: ft = new MainPaperFragment(); break; default: break; } return ft; } @Override public int getCount() { // TODO Auto-generated method stub return MainActivity.this.tabTitle.length; } }
import android.support.v4.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.example.kuhua.R; public class MainPaperFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // TODO Auto-generated method stub View MainPaperFragmentView = inflater.inflate(R.layout.mainpaperfragmentview, container,false); return MainPaperFragmentView; } @Override public void onActivityCreated(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onActivityCreated(savedInstanceState); } }
在上述fragment中 Fragment ft = new MainPaperFragment()本质上没有错,是一种多态,可是一般开发中总easy报错;原因当然在自己,我们在用Fragment的时候大体上知道是导入的import android.support.v4.app.Fragment可是在自己定义Fragment的时候easy直接用了系统的import android.app.Fragment这样就造成了所使用的api不一致。解决办法就是记得所有都用导入的import android.support.v4.app.Fragment就ok了。