Android之fragment的基本使用
1.在xml中佈局
<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"
>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:id="@+id/fl" >
</FrameLayout>
<LinearLayout android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:background="#c0c0c0">
<Button android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:onClick="btn_message"
android:text="訊息"/>
<Button android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:onClick="btn_context"
android:text="聯絡人"/>
<Button android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:onClick="btn_find"
android:text="發現"/>
</LinearLayout>
</LinearLayout>
2.在主activity中
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
}
//點選按鈕加入 message的 Fragment 即自定義FragmentMessage,在FragmentMessage裡在載入佈局
public void btn_message(View view) {
FragmentMessage=new FragmentMessage();
FragmentManager manager=getFragmentManager();
FragmentTransaction transaction=manager.beginTransaction();
transaction.replace(R.id.fl, message);
transaction.commit();
}
public void btn_context(View view) {
FragmentContext context=new FragmentContext();
FragmentManager manager=getFragmentManager();
FragmentTransaction transaction=manager.beginTransaction();
transaction.replace(R.id.fl, context);
transaction.commit();
}
public void btn_find(View view) {
FragmentFind find=new FragmentFind();
FragmentManager manager=getFragmentManager();
FragmentTransaction transaction=manager.beginTransaction();
transaction.replace(R.id.fl, find);
transaction.commit();
}
}
3.自定義FragmentMessage
package com.example.fragment;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FragmentMessage extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view=inflater.inflate(R.layout.f1, null);
return view;
}
}
4.f1佈局
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#b6c6"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="訊息"
android:textSize="30sp" />
</RelativeLayout>
注意:裝載在主佈局中必須是framelayout!!
其中,動態動態載入是固定格式。