模块化Activity-Fragment

来源:互联网 发布:js树状结构 编辑:程序博客网 时间:2024/04/27 09:36

Creating A Fragment

你可以把Fragment看成是Activity一个模块化的部分,它有自己的生命周期,可以接受用户的输入,当Activity运行时也可添加或者删除Fragment。这部分课程,我们使用Support Library,继承Fragment。硬件最低要求是android 1.6

create a Fragment Class

我们通过继承Fragment类来创建一个Fragment。然后通过重新实现它的生命周期函数来插入你的应用逻辑。与使用Activity的方式很像。但是有个地方不同是你必须在onCreate()函数中来定义布局。实际上,这是唯一一个你用到的回调函数来让你的Fragment运行起来。如下:

import android.os.Bundle;import android.support.v4.app.Fragment;import android.view.LayoutInflater;import android.view.ViewGroup;public class ArticleFragment extends Fragment {    @Override     public View onCreateView(LayoutInflater inflater, ViewGroup container,        Bundle savedInstanceState) {        // Inflate the layout for this fragment         return inflater.inflate(R.layout.article_view, container, false);    } } 

像Activity一样,一个Fragment需要实现其他的生命周期回调函数来让你在添加和删除一个Fragment时来管理它的状态。比如当一个Activity接收到onPause()命令,Fragment也会执行onPause()

使用xml文件来向Activity中添加Fragment

因为fragment是可以重复利用,模块化的组件,所以每个Fragment都要与一个父FragmentActivity关联。你可以通过Activity的布局xml文件来实现fragment与activity的关联
注意:FragmentActivity是support Library提供的一个特殊Activity来在API 11版本一下的机器上管理Fragment的。如果你的版本是API 11或者以上,则可以使用正常的Activity
以下是一个例子

<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>

然后运用在你的Activity:

import android.os.Bundle;import android.support.v4.app.FragmentActivity;public class MainActivity extends FragmentActivity {    @Override     public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.news_articles);    } } 

如果使用v7 appcompat library,你的Activity应该继承AppCompatActivity,它是FragmentActivity的一个子类。
注意:当你将定义在布局xml文件中的fragment添加到Activity中,你不能在运行期间将Fragment移除。如果你打算在用户交互期间将Fragment换入换出,你必须在Activity初次打开的时候将Fragment添加到Activity中

0 0