【Android开发之UI】创建一个片段
?
1 2 3 4 5 6 7 8 910111213
import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.ViewGroup; public class ArticleFragment extends { @Override public onCreateView(, , ) { // Inflate the layout for this fragment return .inflate(.layout.article_view, , false); } }就跟activity一样,fragment也应该要实现其他的生命周期方法来管理它的状态,比如当fragment被activity添加或者删除,当activity生命周期状态转换时(类似这种操作都会影响到fragment的状态)。例如,当activity的onPuase()方法被调用的时候,所有activity中的fragment也都会接收到onPause()方法的调用。
更多关于fragment生命周期和回调函数的方法都可以在Fragment?开发指南中找到。
因为fragment是可重用的,模块化的UI组件,每一个Fragment实例必须与父类FragmentActivity相关联。你可以通过在你Activity布局XML文件中定义每一个fragment来获得关联。
注意:FragmentActivity是在系统版本低于API level 11时由Support Library提供用来管理fragment的特殊activity。如果你支持的最低系统版本是API level 11或者更高,那你可以直接使用常规的Activity。
以下是一个例子,当设备屏幕被认为“大”的时候,一个布局文件添加了两个fragment到activity
译者注:当屏幕比较大的时候(比如平板)是可以同时显示两个fragment的,但是屏幕比较小(比如普通手机)同一时间只能显示一个fragment,这是由于它们的屏幕尺寸造成的,后续的课程也会提到这个
这个布局文件被指定在“高”分辨率的目录名下。(译者注:请注意下面xml的目录结构:是在res目录下的layout-large目录下,这样的目录下存放的文件通常都是用来支持高分辨率的布局文件)
res/layout-large/news_articles.xml:
1 2 3 4 5 6 7 8 9101112131415161718
<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>
注:更多关于为不同屏幕大小创建布局,请参照Supporting Different Screen Sizes(支持不同的屏幕大小)
这里展示了在activity中怎样运用这个布局:
1 2 3 4 5 6 7 8 910
import android.os.Bundle; import android.support.v4.app.FragmentActivity; public class MainActivity extends { @Override public void onCreate() { super.onCreate(); (.layout.news_articles); } }?
注意:当你通过在布局XML文件中定义fragment以达到添加一个fragment到activity中时,你不能在运行时移除此fragment。如果你计划在用户交互期间使fragment交替替换,那你必须在activity第一次启动时将fragment添加进去,我们将会在下一节课中演示。