摘要:[Android] Fragment
Fragment 可以將畫面分成多個畫面,透過Fragment可以讓Android畫面顯示更有彈性。
STEP1:建立Fragment 使用的介面布局檔。
Fragment_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<TextView
android:id="@+id/tvName"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="Name:" />
<EditText
android:id="@+id/edName"
android:layout_width="0dp"
android:layout_weight="4"
android:layout_height="wrap_content"
android:ems="10" >
</EditText>
</LinearLayout>
STEP2:新增一個繼承自Fragment的Class。
MyFragment.java
package com.example.fragment1;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class MyFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle saveInstanceState)
{
return inflater.inflate(R.layout.fragment_layout, container, false);
}
}
STEP3:新增一個Include MyFragment的 Layout。
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<fragment android:id="@+id/frag"
android:name="com.example.fragment1.MyFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>