您的位置:首页 > 移动开发 > Android开发

安卓初学-创建Fragment(Creating a Fragment)

2015-12-01 09:35 423 查看
1、Fragment主要在API 11以后直接使用,在Android1.6以前需使用支持库v4 library,如果在API 7以后也可以使用v7 appcompat library。

2、创建Fragment类(使用v4支持库):

(1)类继承自Fragment,必须要重写onCreateView方法

(2)你也可以实现其他生命周期方法,如onPause(),注意它依赖于activity的生命周期。

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.ViewGroup;

public class ArticleFragment ext
4000
ends 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);
}
}


3、用xml增加一个Fragment到Activity

res/layout-large/news_articles.xml

<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);
}
}


(1)注意每个Fragment类必须关联一个父FragmentActivity,且运行时不能移除fragment。

(2)如果要交互,必须在activity开始启动时将fragment加入进去。

(3)如果用v7包需继承fragmentActivity的子类AppCompatActivity。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android api