1.简单
1.1布局,新建一个fragment_blank.xml布局文件
1.2新建一个MyFragment的Java文件<?xml version="1.0" encoding="utf-8"?> <LinearLayout 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:orientation="vertical" tools:context="com.rj141.sb.fragmentdemo01.MainActivity"> <TableLayout android:stretchColumns="1" android:layout_width="match_parent" android:layout_height="wrap_content"> <TableRow> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/name" /> <EditText android:layout_width="wrap_content" android:layout_height="wrap_content" android:hint="" /> </TableRow> <TableRow> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/password" /> <EditText android:layout_width="wrap_content" android:layout_height="wrap_content" android:hint="" /> </TableRow> </TableLayout> <LinearLayout android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content" style="?android:attr/buttonBarStyle"> <Button android:layout_weight="1" android:layout_width="0dp" style="?android:attr/buttonBarButtonStyle" android:layout_height="wrap_content" android:text="@string/login"/> <Button android:layout_weight="1" android:layout_width="0dp" style="?android:attr/buttonBarButtonStyle" android:layout_height="wrap_content" android:text="@string/exit"/> </LinearLayout> </LinearLayout>
1.3修改activity.xml布局文件public class MyFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_blank,container,false); } }
1.4 MainActivity.class文件不变<?xml version="1.0" encoding="utf-8"?> <LinearLayout 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:orientation="vertical" tools:context="com.rj141.sb.fragmentdemo01.MainActivity"> <fragment android:name="com.rj141.sb.fragmentdemo01.MyFragment" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/id_fragment"/> </LinearLayout>
解释其中代码:
android:stretchColumns="1" 设置所用行的第二列为扩展列,如果有三列的话,剩余空间由第二列补齐,即会行都会填满
android:shrinkColumns=“1” 设置所用行第二列为收缩列,即是第二列所占空间收缩变得很小
android:stretchColumns="0" 设置所用行的第二列为扩展列,即中间很大空间是空的,没有任何东西。
创建该Fragment的视图:LayoutInflater.inflate方法解析
activity.xml布局文件是固定的形式http://blog.youkuaiyun.com/xiahao86/article/details/43453529
2.有侧边栏的Fragment
http://blog.youkuaiyun.com/loongggdroid/article/details/12288379