安卓初学-创建Fragment(Creating a Fragment)
2015-12-01 09:35
417 查看
1、Fragment主要在API 11以后直接使用,在Android1.6以前需使用支持库v4 library,如果在API 7以后也可以使用v7 appcompat library。
2、创建Fragment类(使用v4支持库):
(1)类继承自Fragment,必须要重写onCreateView方法
(2)你也可以实现其他生命周期方法,如onPause(),注意它依赖于activity的生命周期。
3、用xml增加一个Fragment到Activity
res/layout-large/news_articles.xml
Activity如下:
(1)注意每个Fragment类必须关联一个父FragmentActivity,且运行时不能移除fragment。
(2)如果要交互,必须在activity开始启动时将fragment加入进去。
(3)如果用v7包需继承fragmentActivity的子类AppCompatActivity。
2、创建Fragment类(使用v4支持库):
(1)类继承自Fragment,必须要重写onCreateView方法
(2)你也可以实现其他生命周期方法,如onPause(),注意它依赖于activity的生命周期。
import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.ViewGroup; public class ArticleFragment ext 4000 ends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.article_view, container, false); } }
3、用xml增加一个Fragment到Activity
res/layout-large/news_articles.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="fill_parent"> <fragment android:name="com.example.android.fragments.HeadlinesFragment" android:id="@+id/headlines_fragment" android:layout_weight="1" android:layout_width="0dp" android:layout_height="match_parent" /> <fragment android:name="com.example.android.fragments.ArticleFragment" android:id="@+id/article_fragment" android:layout_weight="2" android:layout_width="0dp" android:layout_height="match_parent" /> </LinearLayout>
Activity如下:
import android.os.Bundle; import android.support.v4.app.FragmentActivity; public class MainActivity extends FragmentActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.news_articles); } }
(1)注意每个Fragment类必须关联一个父FragmentActivity,且运行时不能移除fragment。
(2)如果要交互,必须在activity开始启动时将fragment加入进去。
(3)如果用v7包需继承fragmentActivity的子类AppCompatActivity。
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- Android IPC进程间通讯机制
- Android Manifest 用法
- [转载]Activity中ConfigChanges属性的用法
- Android之获取手机上的图片和视频缩略图thumbnails
- Android之使用Http协议实现文件上传功能
- Android学习笔记(二九):嵌入浏览器
- android string.xml文件中的整型和string型代替
- i-jetty环境搭配与编译
- android之定时器AlarmManager
- android wifi 无线调试
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- android 代码实现控件之间的间距
- android FragmentPagerAdapter的“标准”配置
- Android"解决"onTouch和onClick的冲突问题
- android:installLocation简析
- android searchView的关闭事件