Android 上的界面展示都是通过 Activity 实现的,Activity 很常用,想必大家都已经很熟悉了。但是Activity也有它的局限性,同样的界面在手机上显示可能很好看,在平板上就未必了,因为平板的屏幕非常大,手机的界面放在平板上可能会有过分被拉长、控件间距过大等情况。这个时候更好的体验效果是在Activity中嵌入“小Activity”,然后每个“小Activity”又可以拥有自己的布局。因此,我们今天的主角Fragment登场了。
我们先通过一个小例子来体会一下 Fragment 的作用。
1. 在layout文件夹下新建一个名为fragment_list.xml的布局文件:
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is fragment list"
android:textColor="#000000"
android:textSize="25sp" />
2. 然后新建一个类ListFragment,这个类是继承自Fragment的:
package net.nowamagic.nm_painting_v1;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class ListFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
//return super.onCreateView(inflater, container, savedInstanceState);
return inflater.inflate(R.layout.fragment_list, container, false);
}
}
3. 打开activity_main.xml作为主 Activity 的布局文件,在里面加入刚才Fragment的引用,使用android:name前缀来引用具体的Fragment:
android:id="@+id/fragment_list"
android:name="net.nowamagic.nm_painting_v1.ListFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1" />
就这样就完成了,很简单吧?效果: