例如,新聞應用可以使用一個片段在左側顯示文章列表,使用另一個片段在右側顯示文章 — 兩個片段並排顯示在一個 Activity 中,每個片段都具有自己的一套生命週期回調方法,並各自處理自己的用戶輸入事件。 因此,用戶不需要使用一個 Activity 來選擇文章,然後使用另一個 Activity 來閱讀文章,而是可以在同一個 Activity 內選擇文章並進行閱讀,如下圖中的平板電腦佈局所示(圖片來源android官方文檔)。
Fragment的生命週期
Fragment的生命週期直接受Activity的生命週期影響
創建Fragment要創建一個類繼承Fragment就可以了,通過重寫onCreateView()方法可以加載Fragment需要加載的佈局
Fragment的靜態使用:
MainActivity.java
package com.example.createfragment_01;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Window;
/**
* 靜態使用Fragment
* 步驟:
* 1.首先創建一個Fragment類繼承於Fragment,重寫onCreateView()方法,設置Fragment的佈局
* 2.再到Activity中聲明Fragment,使用方式與view相同
*
* 例子介紹:2個Fragment構成一個Activity的佈局,一個是標題fragment,一個是內容Fragment
*/
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 去除原有的標題欄
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
}
}
TitleFragment.java
package com.example.createfragment_01.fragment;
import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.Toast;
import com.example.createfragment_01.R;
/**
* 創建和使用Fragment的步驟:
* 1.創建子類繼承Fragment
* 2.重寫onCreateView()方法,該方法主要定義Fragment的佈局,以view對象的形式返回fragment的視圖
* 3.將Fragment引入到Activity中
*/
public class TitleFragment extends Fragment {
/**
* onCreateView()表示Fragment第一次創建繪製用戶界面時系統回調的方法
* 返回值view:表示當前加載的fragment視圖,如果fragment不提供視圖可以返回null
* 參數:
* LayoutInflater inflater:表示佈局加載器或者填充器,將xml文件轉化成view對象
* ViewGroup container:表示當前fragment插入Activity的佈局視圖對象
* Bundle savedInstanceState:表示儲存上一個fragment的信息
*/
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
// 表示將指定資源的xml文件轉換成具體的view對象,inflate(表示加載xml文件的資源id,null)
View view = inflater.inflate(R.layout.fragment_title,null);
RelativeLayout relativeLayout = view.findViewById(R.id.rl_layout);
relativeLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getActivity(), "我是標題欄", Toast.LENGTH_SHORT).show();
}
});
return view;
}
}
fragment_title.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/rl_layout"
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#000000">
<ImageView
android:id="@+id/iv_back"
android:layout_width="35dp"
android:layout_height="35dp"
android:layout_centerVertical="true"
android:paddingLeft="15dp"
android:scaleType="centerCrop"
android:src="@drawable/ic_chevron_left_white_24dp" />
<TextView
android:id="@+id/tv_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="@string/title"
android:textColor="#fcfbfb"
android:textSize="18sp" />
<ImageView
android:id="@+id/iv_menu"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_centerVertical="true"
android:layout_alignParentRight="true"
android:paddingRight="15dp"
android:scaleType="centerCrop"
android:src="@drawable/ic_more_vert_white_24dp" />
</RelativeLayout>
ContentFragment.java
package com.example.createfragment_01.fragment;
import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.createfragment_01.R;
public class ContentFragment extends Fragment {
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_content,null);
return view;
}
}
fragment_content.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">
<TextView
android:id="@+id/tv_content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/content"
android:textSize="30sp"
android:gravity="center"
android:textStyle="bold"/>
</LinearLayout>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<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"
tools:context="com.example.createfragment_01.MainActivity">
<fragment
android:id="@+id/fragment_title"
android:name="com.example.createfragment_01.fragment.TitleFragment"
android:layout_width="match_parent"
android:layout_height="50dp" />
<fragment
android:id="@+id/fragment_content"
android:name="com.example.createfragment_01.fragment.ContentFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@id/fragment_title" />
</RelativeLayout>
效果圖
Fragment的動態使用及動態切換:
MainActivity.java
package com.example.fragmentchange;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.RadioButton;
import com.example.fragmentchange.fragment.ChatFragment;
import com.example.fragmentchange.fragment.ContactsFragment;
import com.example.fragmentchange.fragment.DiscoverFragment;
import com.example.fragmentchange.fragment.MeFragment;
/**
* 動態添加fragment
* 具體4個步驟
*/
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private FragmentManager manager;
private FragmentTransaction transaction;
private RadioButton rb_chat,rb_contacts,rb_discover,rb_me;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
// 1.創建Fragment的管理器對象
manager = getFragmentManager();
// 2.獲取Fragment的事務對象並且開啓事務
transaction = manager.beginTransaction();
// 3.調用事務中相應的動態操作Fragment的方法執行 add(表示動態添加位置的資源id,表示添加的fragment對象)
// 設置默認爲微信頁面
transaction.add(R.id.ll_content,new ChatFragment()); // 將ChatFragment動態添加到ll_content的位置
// transaction.remove(new ChatFragment()); // remove(需要移除的fragment對象)
// transaction.replace(arg0,arg1); // replace(表示被替換fragment的資源id,表示替換者fragment對象)
// 4.提交事務
transaction.commit();
}
// 初始化視圖
public void initView(){
rb_chat = findViewById(R.id.rb_chat);
rb_contacts = findViewById(R.id.rb_contacts);
rb_discover = findViewById(R.id.rb_discover);
rb_me = findViewById(R.id.rb_me);
rb_chat.setOnClickListener(this);
rb_contacts.setOnClickListener(this);
rb_discover.setOnClickListener(this);
rb_me.setOnClickListener(this);
}
/**
* 點擊RadioButton觸發的事件
*/
@Override
public void onClick(View v) {
// 這裏的事務創建必不可少(否則程序點擊就會崩潰)
transaction = manager.beginTransaction();
switch (v.getId()){
case R.id.rb_chat:
transaction.replace(R.id.ll_content,new ChatFragment());
break;
case R.id.rb_contacts:
transaction.replace(R.id.ll_content,new ContactsFragment());
break;
case R.id.rb_discover:
transaction.replace(R.id.ll_content,new DiscoverFragment());
break;
case R.id.rb_me:
transaction.replace(R.id.ll_content,new MeFragment());
break;
}
transaction.commit();
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<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"
tools:context="com.example.fragmentchange.MainActivity">
<!--展示內容界面-->
<LinearLayout
android:id="@+id/ll_content"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" />
<!--展示切換標籤-->
<LinearLayout
android:id="@+id/ll_bottom"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_alignParentBottom="true"
android:orientation="horizontal">
<RadioGroup
android:id="@+id/rg_home"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#f7e3e3"
android:orientation="horizontal">
<!--button的@null是去除默認的圓圈(@不能忘)-->
<RadioButton
android:id="@+id/rb_chat"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:textSize="15sp"
android:button="@null"
android:drawableTop="@drawable/ic_chat_bubble_outline_green_a700_24dp"
android:gravity="center"
android:text="@string/chat" />
<RadioButton
android:id="@+id/rb_contacts"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:textSize="15sp"
android:button="@null"
android:gravity="center"
android:drawableTop="@drawable/ic_contacts_green_a700_24dp"
android:text="@string/contacts" />
<RadioButton
android:id="@+id/rb_discover"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:button="@null"
android:textSize="15sp"
android:drawableTop="@drawable/ic_discover_green_a700_24dp"
android:gravity="center"
android:text="@string/discover" />
<RadioButton
android:id="@+id/rb_me"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:button="@null"
android:textSize="15sp"
android:drawableTop="@drawable/ic_me_green_a700_24dp"
android:gravity="center"
android:text="@string/me" />
</RadioGroup>
</LinearLayout>
</RelativeLayout>
CharFragment.java
package com.example.fragmentchange.fragment;
import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.fragmentchange.R;
public class ChatFragment extends Fragment {
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_chat,null);
}
}
fragment_chat.xml
<?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">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/tv_chat"
android:text="@string/chat_page"
android:gravity="center"
android:textSize="20sp"/>
</RelativeLayout>
剩下的contacts,discover,me跟chat的內容基本都一樣
上效果圖:
v4包下的Fragment使用:
Fragment是android3.0之後引入的UI組件,爲了兼容sdk3.0之前的版本,就出現了supportV4包。
1.導包的時候記得都必須導入v4包下的fragment
2.動態引入fragment時Activity要繼承FragmentActivity
3.獲取Fragment管理器對象就要是getSupportFragmentManager()