fragment作用
同一程序中切换界面 比activity轻快,灵活.fragment代码示例
ide : android studio 1.2
sdk : 22
package com.example.f6k5i8.lfragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class AnotherFragment extends <span style="color:#33ccff;">Fragment</span> {
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
//R.layout.fragment_another是本fragment对应的资源文件,container是主布局,
View root = inflater.inflate(R.layout.fragment_another, container, false);
root.findViewById(R.id.btnBackFragment).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getFragmentManager().popBackStack();
}
});
return root;
}
}
1.注意 fragment的包
注意这里的基类fragment 是 import android.support.v4.app.Fragment; 里的.不是android.app里的
2.界面配置
fragment也有界面布局xml文件: fragment_another.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/fragmentB_text"
android:id="@+id/anotherFragment"
android:layout_gravity="center_horizontal" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAllCaps="false"
android:text="后退到上一个Fragment"
android:id="@+id/btnBackFragment"
android:layout_gravity="center_horizontal" />
</LinearLayout>
3.fragment与layout.xml关联
AnotherFragment与它对应的layout.xml关联的代码是 onCreateView函数中的下面语句;
View root = inflater.inflate(R.layout.fragment_another, container, false);
4.跳转到一个新的fragment示例代码
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
getFragmentManager().beginTransaction()
.addToBackStack("AnotherFragment的标记")
.replace(R.id.container, new AnotherFragment())
.commit();
有add,有replace等多种方法.
参数R.id.container是主容器的id,它在activity_main.xml中定义,且不能用R.layout.activity_main.
参数new AnotherFragment() 是被添加的fragment子视图.
注意 addToBackStack 将打开的fragment压进栈.这样方便返回
5.从新fragment返回
前提是本fragment在打开时是addToBackStack里的
getFragmentManager().popBackStack();