Fragment入门
2016-04-14 本文已影响94人
蛋蛋不哭
关于Fragment让我们再来温习一遍
Fragment的生命周期:
Fragment.png注:
说起Android中的Fragment,在使用的时候稍加注意,就会发现存在以下两种:
v4包中的兼容Fragment,android.support.v4.app.Fragment
普通的Fragment,android.app.Fragment
- Fragment有两种写法:
- 静态
- 动态
1.静态
主布局xml
<fragment
android:id="@+id/f"
class="com.abc.Fragmentone"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
其他布局就是普通的布局
创建Fragment.java文件(主布局的Acticity不需要改动)
public class Fragmentone extends Fragment{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.Fragment, null);
return view;
}
}
2.动态
主布局稍有改动,分布局不变
<FrameLayout
android:id="@+id/fl"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
</FrameLayout>
在Activity中调用Fragment
public class FrigenmentDemoActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//1.创建Fragment
Fragmentone fragmentone = new Fragmentone();
//通过FragmentManager来开启
FragmentTransaction ft = getFragmentManager().beginTransaction();
//通过事物动态添加或替换
ft.add(R.id.fl, fragmentone);
//提交事务
ft.commit();
}
}
Fragment还是 原来的Fragment
public class Fragmentone extends Fragment{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.Fragment, null);
return view;
}
}