创建一个Fragment类
兼容的Fragmgent要用到v4包或者是v7包也行。
需要继承于Fragment类,重写主要的生命周期函数。一个不同的是,我们必须使用onCreateView()这个回调方法来定义我们的layout(布局)。
简单的例子:
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);
}
}
使用XML添加一个Fragment
<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>
在FragmentActivity中的代码:
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包的话,就要用ActionBarActivity而不是FragmentActivity了。
!!!当我们在XML布局中添加一个Framgment,就不可能在运行时移除这个Fragment。如果想要在与用户交互的时候动态的换入换出,我们一定要在Activity第一次启动的时候添加它。