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