——主窗体与碎片 【若对该知识点有更多想了解的,欢迎私信博主~~】
android.intent.action.MAIN决定应用程序最先启动的Activity
android.intent.category.LAUNCHER决定应用程序是否显示在程序列表里
android:launchMode="standard"加载模式(4种)
加载模式说明Standard 标准模式每次启动一个Activity都会又一次创建一个新的实例入栈,无论这个实例是否存在SingleTop 栈顶复用模式要创建的Activity已经处于栈顶时,会直接复用栈顶的Activity;若要创建的Activity不处于栈顶,会创建一个新的Activity入栈SingleTask 栈内复用模式创建的Activity已经处于栈中时,不会创建新的Activity,而是将存在栈中的Activity上面的其他Activity所有销毁,使它成为栈顶SingleInstance 单实例模式此模式的Activity仅仅能单独位于一个任务栈中Fragment是依赖于Activity的,不能独立存在的。
一个Activity里可以有多个Fragment。
一个Fragment可以被多个Activity重用。
Fragment有自己的生命周期。
能在Activity运行时动态地添加或删除Fragment。
新建一个class文件继承Fragment
重写onCreateView方法返回一个view
public class Fragment extends Fragment { @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.fm1,null); } }新建的layout文件若不存在,alt+enter快速建立layout文件(create layout view resource 'fm1‘)
静态加载:静态加载就是把Fragment当成普通的控件,直接写在Activity的布局文件中
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#fff"> <fragment android:name="Fragment" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout>动态加载:碎片的动态加载就是在app运行时根据需要加载相应的Fragment显示
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main1); //获取辅助碎片管理器 FragmentManager fm=getSupportFragmentManager(); //开启事务 FragmentTransaction ft=fm.beginTransaction(); //实例化碎片 Fragment f1=new Fragmenthh(); //添加碎片 ft.add(R.id.fl,f1,"1");//R.id.fl为主窗体中的FramLayout布局容器 //需要显示的碎片 ft.show(f1); //提交事务 ft.commit(); }