初识Android | 青训营笔记
这是我参与「第四届青训营」笔记创作活动的的第3天
Fragment
Fragment表示应用界面中可重复使用的一部分。Fragment定义和管理自己的布局,具有自己的生命周期,并且可以处理自己的输入事件。Fragment不能独立存在,而是必须由Activity或另一个Fragment托管。- 解决
Activity间的切换不流畅,轻量切换 - 可以从
startActivityForResult中接收到返回结果,但是View不能 - Activity是屏幕的主体,而Fragment是Activity的一个组成元素。
Fragment的静态加载:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<!--静态加载
通过android:name属性指定Fragment的路径
-->
<fragment
android:id="@+id/fragment1"
android:layout_width="200dp"
android:layout_height="200dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:name="com.example.fragmentdemo.Fragment1"/>
</androidx.constraintlayout.widget.ConstraintLayout>
Fragment的动态加载:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.i("TAG","Activity--onCreate");
//FragmentManager FragmentTransaction
//1.获取Fragment管理器
FragmentManager manager = getSupportFragmentManager();
//2.获取Fragment事务(/开启事务)
FragmentTransaction transaction = manager.beginTransaction();
//3.动态添加Fragment
//参数1:容器id
//参数2:Fragment对象
final Fragment f2 = new Fragment2();
transaction.add(R.id.container,f2);
//4.提交事务
transaction.commit();
}
Android通信组件
- 为什么使用通信组件?:
-
为了UI渲染不卡顿,需要将UI渲染和耗时任务放在不同线程中执行,互不干扰保证UI渲染的流畅性。
-
为了做到第1点,Android默认将UI渲染限制在UI线程中执行
-
- 方法:
-
Handler:
Looper从消息队列中不断去除消息进行处理 -
安排 Message 和 runnables 在将来的某个时刻执行;
-
将要在不同于自己的线程上执行的操作排入队列。(在多个线程并发更新UI的同时保证线程安全。)
-
Binder:Android客户端和服务端进行通信的媒介
-