Fragment的简单使用

来源:互联网 发布:矩阵论教程 张绍飞 pdf 编辑:程序博客网 时间:2024/05/22 03:29

Fragment(碎片)是一种可以嵌入在活动中的UI片段。他能让程序更加合理和充分利用大屏幕空间。

1.fragment有自己的生命周期 如图所示:

2.Fragment必须依赖于Activity存在。
3.Fragment 通过getActivity()可以获取所在的Activity;Activity通过FragmentManger的findFragmentById()或者findFragmentByTag()获取Fragment。
举个栗子:
1新建一个类AFragment继承Fragment(有两个Fragment,分别是android.app.Fragment和support-v4的,support-v4在安卓所有的版本保持一致,而support-v4在Android4.2之前运行会崩溃。)这里面回调了两个方法。一个是
onCreateView加载fragment中的视图。另一个是onViewCreated。
public class AFragment extends Fragment{    private TextView mTextView;    @Nullable    @Override    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {        View view=inflater.inflate(R.layout.fragment_a,container,false);        return view;    }    @Override    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {        super.onViewCreated(view, savedInstanceState);        mTextView= (TextView) view.findViewById(R.id.tv_title);    }}
AFragment的视图代码:
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"              android:orientation="vertical"              android:gravity="center"              android:layout_width="match_parent"              android:layout_height="match_parent">    <TextView        android:id="@+id/tv_title"        android:gravity="center"        android:textSize="40sp"        android:text="我是AFragment"        android:textColor="#000"        android:layout_width="match_parent"        android:layout_height="wrap_content"/></LinearLayout>
BFragment的一切与A类似记得把里面的A换成B;
2.对Activity代码进行操作
public class MainActivity extends AppCompatActivity {    private  AFragment mAFragment;    private  BFragment mBFragment;    private Button mButton;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        mAFragment=new AFragment();        getFragmentManager().beginTransaction().add(R.id.fl,mAFragment).commitAllowingStateLoss();        mButton= (Button) findViewById(R.id.change);        mButton.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                if (mBFragment==null){                    mBFragment=new BFragment();                }                getFragmentManager().beginTransaction().replace(R.id.fl,mBFragment).commitAllowingStateLoss();            }        });    }}

ok完成,运行,看下效果如图