首页 > 代码库 > android.app.Fragment与android.support.v4.app.Fragment不一致

android.app.Fragment与android.support.v4.app.Fragment不一致

在看法中用到的Fragment在类型转换的时候很容易出现这种问题:

对比代码:

	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()本质上没有错,是一种多态,但是一般开发中总容易报错;原因当然在自己,我们在用Fragment的时候大体上知道是导入的import android.support.v4.app.Fragment但是在自定义Fragment的时候容易直接用了系统的import android.app.Fragment这样就造成了所使用的api不一致。解决的方法就是记得全部都用导入的import android.support.v4.app.Fragment就ok了!

android.app.Fragment与android.support.v4.app.Fragment不一致