最近想用用fragment开发几个界面,没想到上手写xml配置还不顺利,一怒之下直接动态添加,网上介绍的资源太多了,随便看看几乎都一样,就是把android developer上面的翻译了一下,看来看去还是直接去看官方文档好
创建fragment
要创建一个fragment就类似创建Activity一样,需要重写一个onCreateView(...)方法:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
return inflater.inflate(R.layout.fragment_login, container, false);
}
其中fragment_login.xml就是fragment的布局
添加fragment
在Activity中动态添加fragment,必须把这个fragment添加到一个容器中
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
</FrameLayout>
然后通过FragmentManager的beginFragmentTransaction().add()添加,最后commit()提交
对于android3.0以下的需要support包对应的方法
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.framecontainer);
if(findViewById(R.id.fragment_container) != null) {
if(savedInstanceState != null) {
return;
}
}
LoginFragment firstFragment = new LoginFragment();
// In case this activity was started with special instructions from an
// Intent, pass the Intent's extras to the fragment as arguments
firstFragment.setArguments(getIntent().getExtras());
// Add the fragment to the 'fragment_container' FrameLayout
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container, firstFragment).commit();
}
替换fragment
替换fragment的时候用到的方法是beginFragmentTransaction().replace(),在替换之后之前的fragment的onDestroyView()以及onDestroy()方法会被调用,如果不想onDestroy()被调用,即希望用户通过back键来回退到之前的fragment,可以在提交fragment事务之前调用addToBackStack()方法。
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack so the user can navigate back
transaction.addToBackStack(null);
// first two anim-file control login button clicked animation, the other control back key animation
transaction.setCustomAnimations(R.anim.slide_to_left_enter, R.anim.slide_to_left_exit,
R.anim.slide_to_right_enter, R.anim.slide_to_right_exit);
transaction.replace(R.id.fragment_container, newFragment);
// Commit the transaction
transaction.commit();
这里可以设置两个fragment切换时的动画效果,下节具体介绍各种切换效果。