1.创建一个类,继承v4.Fragment
public abstract class BaseFragment extends Fragment {}
2.1.抽取,因为menufragment和homefragment都会是执行初始化数据和显示界面操作,所以相同的操作抽取到父类
2.1.1创建BaseFragement
public abstract class BaseFragment extends Fragment {}2.1.2子类继承basefragment
public class MenuFragment extends BaseFragment {}2.2.因为homefragment和menufragment加载的界面和显示的数据不一样,但是父类无法实现,所以父类创建两个抽象方法,让子类根据自己的特性去实现
2.2.1在baseFragment中创建两个抽象方法
/** * 加载显示布局 */ public abstract View initView(); /** * 初始化加载数据 */ public abstract void initData();2.2.2.子类实现抽象方法,在menufragment中
public class MenuFragment extends BaseFragment { @Override public View initView() { // TODO Auto-generated method stub return null; } @Override public void initData() { // TODO Auto-generated method stub }
package rain.base; import android.content.Context; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; /** * Created by:Rain on 2016/2/21 18:08 * E-mail: [email protected] * Url: http://blog.csdn.net/sinat_33680954 * 签名: 通过改变自我适应万变的世界 ---Rain */ //因为homeFragment和menuFragment加载的界面和数据不一样,父类无法实现 //所以父类创建俩个抽象方法,让子类根据自己的特性去实现 public abstract class BaseFragement extends Fragment { public View view; public Context context; // 1.初始化创建的操作 @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); context = getActivity(); } //初始化fragment的布局 @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { view = initView(); return view; } // 3.初始化fragment的数据 @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { initData(); super.onActivityCreated(savedInstanceState); } /** * 加载显示布局 */ public abstract View initView(); /** * 初始化加载数据 */ public abstract void initData(); }
/** * 添加HomeFragment的操作 */ private void setHomeFragment() { HomeFragment homeFragment = new HomeFragment(); getSupportFragmentManager().beginTransaction() .replace(R.id.fl_home,homeFragment,"HOME").commit(); } /** * 添加menufragment的操作 */ private void setMenuFragment() { MenuFragment menuFragment = new MenuFragment(); //获取Fragment管理器并开启事务 getSupportFragmentManager().beginTransaction() //将布局替换成fragment .replace(R.id.menu,menuFragment,"MENU").commit(); }