標籤:
1.使用xml標籤
1.1定義兩個重要屬性
<fragment
android:id="@+id/fregment_top"
android:layout_width="match_parent"
android:layout_height="220dp"
android:layout_marginTop="80dp"
android:name="com.lzh.fragment_study.Framgment_first"
/>
1.2實現一個繼承自Fragment的新類
public class Framgment_first extends Fragment {
public Framgment_first() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
1.3建立一個Fragment的layout檔案 fragment_main
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.lzh.fragment_study.MainActivity$PlaceholderFragment" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world"
/>
</RelativeLayout>
2.通過JAVA代碼實現
//在程式中加入Fragment
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
ExampleFragment fragment = new ExampleFragment();
fragmentTransaction.add(R.id.container, fragment);
fragmentTransaction.commit();
getSupportFragmentManager().beginTransaction()
.add(R.id.container,new Framgment_first()).commit();
android 之fragment建立