Pro Android学习笔记(三七):Fragment(2):基础小例子

来源:互联网 发布:北京邮电网络教育 编辑:程序博客网 时间:2024/05/16 23:47

小例子运行效果

这是一个书名和书简介的例子。运行如下图。Activity由左右两个Fragment组成,左边显示书名列表,右边显示书的简介。用户点击左边的书名,右边fragment则自动显示该书的简介。

Pre-step:一点准备

小例子用于学习fragment,书名和简介用数组进行存贮,放在BooksInfo类中,如下:

public class BooksInfo {
    public static String TITLES[] = {
        "Henry IV (1)",
        "Henry V",
        "Henry VIII",
        "Romeo and Juliet",
        "Hamlet",
        "The Merchant of Venice",
        "Othello"

    };
    public static String DIALOGUE[] = {
        "So shaken as we are, so wan with care,…..",
        "O for a Muse of fire, that would ascend,……",
        "I come no more to make you laugh: things now, ……",
        "Two households, both alike in dignity, ……",
        "Though yet of Hamlet our dear brother's death …… ",
        "The quality of mercy is not strain'd, ……",
        "It is Othello's pleasure, our noble and valiant ……"

    };
}

Step 1:Activity的布局

下面的Activity的layout布局。从小例子看,左边的fragment属于主导,右边的fragment呈现的内容,根据左边所确定,左右两边所占空间的比例为1:2。具体的layout文件fragment_basic.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="horizontal" >

    <!-- 设置左边Fragment的id,并直接通过class属性给出该fragement对应的类为TitleFragment,需要注意fragment并不是view,不支持里面子tag,即不支持<fragment …. ><…></fragment>的格式  -->
    <fragment class="com.wei.flowingflying.pro.ProFragment.TitleFragment"
        android:id="@+id/titles"

        android:layout_weight="1"
        android:layout_width="0px"
        android:layout_height="match_parent"
/> 
     <!-- 注意:这是FrameLayout,不是fragment,是view,右边fragment的呈现有左边fragment的操作决定,不指定对应的类,可以由不同的类来具体实现UI -->
      <FrameLayout android:id="@+id/details"
            android:layout_weight="2"
            android:layout_width="0px"
            android:layout_height="match_parent"
/>
</LinearLayout>

Activity的代码如下:

public class FragmentBasicTest extends Activity{ 
    @Override
    protected void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.fragment_basic); 
    } 
    
    //根据用户点击书面,具体实现右边的fragment,暂略,以后补充。
    public void showDetails(int index){
        …… 
    }
}

本博文涉及的例子代码,可以在Pro Android学习:Fragment中下载。

相关链接: 我的Android开发相关文章