第四周

在手机中设计,我们可以将新闻标题列表放在一个 Activity 中,将新闻的详细内容放在另一个 Activity 中。

碎片的使用方式

1、新建一个FragmentTest 项目

在一个活动当中添加两个碎片,并让这两个碎片平分活动空间。

新建一个左侧碎片布局left_fragment.xml,代码如下所示:

[html]view plaincopy

android:layout_width="match_parent"

android:layout_height="match_parent"

android:orientation="vertical">

android:id="@+id/button"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_gravity="center_horizontal"

android:text="Button"

/>

这个布局非常简单,只放置了一个按钮,并让它水平居中显示。

2、新建右侧碎片布局right_fragment.xml

[html]view plaincopy

android:layout_width="match_parent"

android:layout_height="match_parent"

android:background="#00ff00"

android:orientation="vertical">

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_gravity="center_horizontal"

android:textSize="20sp"

android:text="This is right fragment"

/>

我们将这个布局的背景色设置成绿色,并放置了一个TextView 用于显示一段文本。

3、新建一个LeftFragment 类,继承自Fragment

注意,这里可能会有两个不同包下的Fragment 供你选择,

建议使用Android.app.Fragment,因为我们的程序是面向Android 4.0以上系统的,

另一个包下的Fragment 主要是用于兼容低版本的Android 系统。

LeftFragment的代码如下所示:

[java]view plaincopy

publicclassLeftFragmentextendsFragment

{

@Override

publicView onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState)

{

View view = inflater.inflate(R.layout.left_fragment, container,false);

returnview;

}

}

这里仅仅是重写了Fragment 的onCreateView()方法,

然后在这个方法中通过LayoutInflater的inflate()方法将刚才定义的left_fragment 布局动态加载进来,

整个方法简单明了。

4、用同样的方法再新建一个RightFragment

[java]view plaincopy

publicclassRightFragmentextendsFragment

{

@Override

publicView onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState)

{

View view = inflater.inflate(R.layout.right_fragment, c

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 用户开发中的布局开发 布局和控件(完成UI设计) 涉及布局layout和控件View 线性布局和相对布局 显示文本...
    董朕阅读 217评论 0 0
  • 碎片是什么 碎片 (Fragment) 是一种可以嵌入在 Activity 当中的 UI 片段,它能让程序更加合理...
    墨栉枫阅读 1,111评论 0 1
  • 动态创建fragment的流程 1.0 新建一个类继承fragment. 2.0 在自定义的fragment里面复...
    左神话阅读 2,235评论 0 3
  • 我是一个聊到感情就会泄气的人,看到周边的亲朋好友的婚姻状态,我就会感慨一个人过得真爽。有一天,和好友聊到感情问题,...
    Roughlay成长日记阅读 302评论 0 0
  • 十一假期已经悄然过去许多天,可是自己却并没有收获到预期的,在自责的同时,也有一些话要对自己说。事情的起源还是要从假...
    木鱼的城堡阅读 419评论 0 1