Fragment知识概要
- Fragment可以作为Activity界面的一部分组成出现
- 可以在一个Activity中同时出现多个fragment,并且一个Fragment也可以在多个Activity中使用
- 在Activity运行过程中,可以添加,移除,替换Fragment
- Fragment可以响应自己的输入事件,并且有自己的生命周期,他们的生命周期会受宿主Activity的生命周期影响
静态加载Fragment
- 创建一个Layout文件,就是我们的Fragment的UI界面
fragment.xml
<?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:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textView"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button"/>
</LinearLayout>
- 创建一个类继承Fragment,然后重写里面的onCreateView方法,将Fragment的Layout变成View
onCreateView()方法
Fragment第一次绘制他的用户界面的时候,系统会调用Fragment的UI,此方法必须返回一个View,如果不显示UI,返回null即可
MyFragment.java
public class MyFragment extends Fragment {
@Override
//会在第一次绘制Fragment的时候调用
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
/*
*参数1(resource):Fragment所需要加载的布局文件
*参数2(root):加载layout的父组件viewGroup
*参数3(attachToRoot):false,不返回父viewGroup(因为已经加载了父viewGroup)
*/
// 将layout布局文件转换成view对象
View view=inflater.inflate(R.layout.fragment, container, false);
TextView text=(TextView)view.findViewById(R.id.textView);//因为所布局的文件已经放在view里了,所以一定要加一个view前缀
text.setText("静态加载");
return view;
}
}
- 在Layout布局文件中声明fragment,android:name属性里是我们上面创建的类,另外,fragment必须用id或tag作为唯一标识
main.xml
<?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:orientation="vertical" >
<!-- name属性指定了在layout中实例化的fragment类 -->
<fragment
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:name="com.example.fragment1.MyFragment"
android:id="@+id/fragment"/>
</LinearLayout>
Activity文件
MainActivity2.java
package com.example.fragment1;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity2 extends Activity{
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
/*通过静态加载的方式已经将fragment加载到了Activity的布局文件中,fragment中的布局文件对于Activity本身而言也是共享里面的
* UI控件的
*/
Button button=(Button) findViewById(R.id.button);
textView=(TextView) findViewById(R.id.textView);
button.setText("改变");
//通过事件监听器改变TextView和Fragment的值
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
textView.setText("textView改变了");
}
});
}
}