Android-fragment简介-fragment的简单使用

时间:2023-03-08 22:21:39

1.fragment简介

在Android3.0版本之前Google还没有推出fragment,在Android3.0版本之后Google推出了fragment,由于Android3.0版本是过渡期版本,fragment真正大量使用是在Android4.0版本之后,已经有了Activity为什么Google还有设计出fragment呢,是因为之前的Android版本一直是为手机考虑,后来慢慢的就决定要多设备发展(例如:平板)所以有了fragment的出现

fragment是一个特殊的控件,fragment是有生命周期的控件,fragment必须在Activity之上运行(意思就是:fragment是被Activity定义和控制的)可以对 fragment 添加、移除、管理 等操作

  Activity / Fragment开发过程中的比较:

  Android-fragment简介-fragment的简单使用

  

    可以理解为:Fragment的出现可以分离Activity代码


2.案例:简单的 Fragment Demo

MyTestFragmentActivity

package liudeli.activity.fragment;

import android.app.Activity;
import android.os.Bundle; import liudeli.activity.R; public class MyTestFragmentActivity extends Activity { @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); setContentView(R.layout.activity_test_fragment);
}
}

MyTestFragmentActivity 的 布局文件

<?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"> <!--
android:id="@+id/fragment" 必须要指定好ID,否则运行会报错
class="liudeli.activity.fragment.MyFragment" 必须要指定class,否则无效果
-->
<fragment
android:id="@+id/fragment"
class="liudeli.activity.fragment.MyFragment"
android:layout_width="wrap_content"
android:layout_height="wrap_content" /> </LinearLayout>

布局 <fragment class 引用的  MyFragment

package liudeli.activity.fragment;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView; public class MyFragment extends Fragment { @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
TextView textView = new TextView(getActivity()); // 不能使用this,因为Fragment父类不是Context
textView.setText("我是MyFragment"); /* 也可以是使用布局加载器加载
View view = inflater.inflate(R.layout.xxx, null);
view.findViewById(R.id.xxx);
view.findViewById(R.id.xxx);
.....
*/
return textView;
}
}

效果:

Android-fragment简介-fragment的简单使用