Android读书笔记之Fragment入门

来源:互联网 发布:普通话模拟测试软件 编辑:程序博客网 时间:2024/06/06 18:59

该读书笔记是自己阅读《Android编程权威指南》和《The.Big.Nerd.Ranch.Guide.2nd.Edition》(《Android编程权威指南》第二版)所做的一些笔记。


首先Fragment要托管在Activity那,所以我们首先创建个MainActivity,代码如下:

package com.example.zhan.fragmenttest;import android.app.Fragment;import android.app.FragmentManager;import android.os.Bundle;import android.support.v4.app.FragmentActivity;public class MainActivity extends FragmentActivity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        FragmentManager fragmentManager = getFragmentManager();        Fragment fragment = fragmentManager.findFragmentById(R.id.fragment_container);        if (fragment == null) {            fragment = new BlankFragment();            fragmentManager.beginTransaction().add(R.id.fragment_container,fragment).commit();        }    }}

其中R.id.fragment_container是MainActivity的布局,作为Fragment的容器视图,代码如下:

<RelativeLayout    xmlns:android="http://schemas.android.com/apk/res/android"    android:id="@+id/fragment_container"    android:layout_width="match_parent"    android:layout_height="match_parent"/>

当然,你不用RelativeLayout,用其他也行。。


BlankFragment就是我们要托管的BlankFragment,该类代码如下:

package com.example.zhan.fragmenttest;import android.app.Fragment;public class BlankFragment extends Fragment {}

这个时候Fragment上什么都没放,空空如也。。

现在你运行一下程序,就是一个白屏,什么也没有,不过其实现在Fragment已经成功托管到了Activity上了。


现在我们可以直接在BlankFragment的布局文件上添加一些组件了,比如添加一个TextView,代码如下:

<LinearLayout android:id="@+id/my_fragment"              xmlns:android="http://schemas.android.com/apk/res/android"              android:layout_width="match_parent"              android:layout_height="match_parent"              android:orientation="vertical">    <TextView        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="Fragment Test"/></LinearLayout>

要让我们添加的TextView显示出来,我们还需要重写Fragment的onCreateView方法,代码如下:

package com.example.zhan.fragmenttest;import android.app.Fragment;import android.os.Bundle;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;public class BlankFragment extends Fragment {    @Override    public View onCreateView(LayoutInflater inflater, ViewGroup container,                             Bundle savedInstanceState) {        View view = inflater.inflate(R.layout.fragment_blank,container,false);        return view;    }}

你再运行程序,屏幕上就会出现"Fragment Test"的字样了,所以现在我们要动界面,直接改Fragment部分就可以了,不用动Activity部分了。


0 0
原创粉丝点击