fragment是一個特殊的控件,fragment是有生命週期的控件,fragment必須在Activity之上運行(意思就是:fragment是被Activity定義和控制的)能夠對 fragment 添加、移除、管理 等操做android
Activity / Fragment開發過程當中的比較:app
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); } }
<?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>
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; } }
效果:ide