Fragment创建静态加载与动态加载详细流程
扫描二维码
随时随地手机看文章
1、静态加载
1、fragment layout
2、fragment类
3、在对应的activity layout中加载 fragment
1、fragment layout
2、fragment class
package com.example.administrator.fragment2; import android.os.Bundle; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import java.util.zip.Inflater; /** * Created by Administrator on 2015/7/22. */ public class Fragment extends android.app.Fragment { @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { /** * 将 layout转成 view对象 */ View view = inflater.inflate(R.layout.fragment,container,false); return view; } }
3.在对应的activity layout中加载 fragment
2动态加载
前两步和静态加载一样
不同的地方在于
package com.example.administrator.fragment2; import android.app.*; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; public class MainActivity extends ActionBarActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //动态加载 fragment Fragment fragment = new Fragment(); //这个是我们自己定义的 Fragment FragmentManager fragmentManager = getFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.addToBackStack(null); //后退按键 允许 fragmentTransaction.add(R.id.linear,fragment); fragmentTransaction.commit(); } }