導航:首頁 > 操作系統 > androidfragments

androidfragments

發布時間:2023-05-29 18:27:36

Ⅰ fragments android 為什麼

Fragments 誕生初衷

自從Android 3.0中引入fragments
的概念,根據詞海的翻譯可以譯為:碎片、片段。其上的是為了解決不同屏幕分辯率的動態和靈活UI設計。大屏幕如平板小屏幕如手機,平板電腦的設計使得其有
更多的空間來放更多的UI組件,而多出來的空間存放UI使其會產生更多的交互,從而誕生了fragments 。fragments 的設計不需要你來親自管理view
hierarchy 的復雜變化,通過將Activity 的布局分散到frament 中,可以在運行時修改activity 的外觀,並且由activity
管理的back stack 中保存些變化。

Fragments 設計理念

在設計應用時特別是Android 應用 ,有眾多的解析度要去適應,而fragments
可以讓你在屏幕不同的屏幕上動態管理UI。例如:通訊應用程序(QQ),用戶列表可以在左邊,消息窗口在灶前右邊的設計。而在手機屏幕用戶列表填充屏幕當點擊
某一用戶時,則彈出對話窗口的設計,如下圖:

Ⅱ 我為什麼主張反對使用Android Fragment

在2011年,基於以下原因我們決定在項目中使用fragments:

在那個時候,我們還沒有支持平板設備-但是我們知道最終將會支持的,Fragments有助於構建響應式UI;

Fragments是view controllers,它們包含可測試的,解耦的業務邏輯塊;

Fragments API提供了返回堆棧管理功能(即把activity堆棧的行為映射到單獨一個activity中);

由於fragments是構建在views之上的,而views很容易實現動畫效果,因此fragments在屏幕切換時具有更好的控制;

Google推薦使用fragments,而我們想要我們的代碼標准化;

自從2011年以來,我們為Square找到了更好的選擇。

關於fragments你所不知道的

復雜的生命周期

Android中,Context是一個上帝對象(god object),而Activity是具有附加生命周期的context。具有生命周期的上帝對象?有點諷刺的稿隱意味。Fragments不是上帝對象,但它們為了彌補這一點,實現了及其復雜的生命周期。

Steve Pomeroy為Fragments復雜的生命周期製作了一張圖表看起來並不可愛:
這里寫圖殲敬芹片氏畢描述

上面Fragments的生命周期使得開發者很難弄清楚在每個回調處要做什麼,這些回調是同步的還是非同步的?順序如何?

難以調試

當你的app出現bug,你使用調試器並一步一步執行代碼以便了解到底發生了什麼,這通常能很好地工作,直到你遇到了FragmentManagerImpl:它是地雷。

下面這段代碼很難跟蹤和調試,這使得很難正確的修復app中的bug:

switch (f.mState) { case Fragment.INITIALIZING: if (f.mSavedFragmentState != null) { f.mSavedViewState = f.mSavedFragmentState.getSparseParcelableArray( FragmentManagerImpl.VIEW_STATE_TAG); f.mTarget = getFragment(f.mSavedFragmentState, FragmentManagerImpl.TARGET_STATE_TAG); if (f.mTarget != null) { f.mTargetRequestCode = f.mSavedFragmentState.getInt( FragmentManagerImpl.TARGET_REQUEST_CODE_STATE_TAG, 0); } f.mUserVisibleHint = f.mSavedFragmentState.getBoolean( FragmentManagerImpl.USER_VISIBLE_HINT_TAG, true); if (!f.mUserVisibleHint) { f.mDeferStart = true; if (newState > Fragment.STOPPED) { newState = Fragment.STOPPED; } } } // ... }

如果你曾經遇到屏幕旋轉時舊的unattached的fragment重新創建,那麼你應該知道我在談論什麼(不要讓我從嵌套fragments講起)。

正如Coding Horror所說,根據法律要求我需要附上這個動畫的鏈接。
這里寫圖片描述

經過多年深入的分析,我得到的結論是WTFs/min = 2^fragment的個數。

View controllers?沒這么快

由於fragments創建,綁定和配置views,它們包含了大量的視圖相關的代碼。這實際上意味著業務邏輯沒有和視圖代碼解耦-這使得很難針對fragments編寫單元測試。

Fragment事務

Fragment事務使得你可以執行一系列fragment操作,不幸的是,提交事務是非同步的,而且是附加在主線程handler隊列尾部的。當你的app接收到多個點擊事件或者配置發生變化時,將處於不可知的狀態。

class BackStackRecord extends FragmentTransaction { int commitInternal(boolean allowStateLoss) { if (mCommitted) throw new IllegalStateException("commit already called"); mCommitted = true; if (mAddToBackStack) { mIndex = mManager.allocBackStackIndex(this); } else { mIndex = -1; } mManager.enqueueAction(this, allowStateLoss); return mIndex; } }

Fragment創建魔法

Fragment實例可以由你或者fragment manager創建。下面代碼似乎很合理:

DialogFragment dialogFragment = new DialogFragment() { @Override public Dialog onCreateDialog(Bundle savedInstanceState) { ... } }; dialogFragment.show(fragmentManager, tag);

然而,當恢復activity實例的狀態時,fragment manager可能會嘗試通過反射機制重新創建這個fragment類的實例。由於這是一個匿名內部類,它的構造函數有一個隱藏的參數,持有外部類的引用。

android.support.v4.app.Fragment$InstantiationException: Unable to instantiate fragment com.squareup.MyActivity$1: make sure class name exists, is public, and has an empty constructor that is public

Fragments的經驗教訓

盡管存在缺點,fragments教給我們寶貴的教訓,讓我們在編寫app的時候可以重用:

單Activity界面:沒有必要為每個界面使用一個activity。我們可以分割我們的app為解耦的組件然後根據需要進行組合。這使得動畫和生命周期變得簡單。我們可以把組件代碼分割成視圖代碼和控制器代碼。

返回棧不是activity特性的概念;我們可以在一個activity中實現返回棧。

沒有必要使用新的API;我們所需要的一切都是早就存在的:activities,views和layout inflaters。

響應式UI:fragments vs 自定義views

Fragments

讓我們看一個fragment的簡單例子,一個列表和詳情UI。

HeadlinesFragment是一個簡單的列表:

public class HeadlinesFragment extends ListFragment { OnHeadlineSelectedListener mCallback; public interface OnHeadlineSelectedListener { void onArticleSelected(int position); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setListAdapter( new ArrayAdapter<String>(getActivity(), R.layout.fragment_list, Ipsum.Headlines)); } @Override public void onAttach(Activity activity) { super.onAttach(activity); mCallback = (OnHeadlineSelectedListener) activity; } @Override public void onListItemClick(ListView l, View v, int position, long id) { mCallback.onArticleSelected(position); getListView().setItemChecked(position, true); } }

接下來比較有趣:ListFragmentActivity到底需要處理相同界面上的細節還是不需要呢?

public class ListFragmentActivity extends Activity implements HeadlinesFragment.OnHeadlineSelectedListener { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.news_articles); if (findViewById(R.id.fragment_container) != null) { if (savedInstanceState != null) { return; } HeadlinesFragment firstFragment = new HeadlinesFragment(); firstFragment.setArguments(getIntent().getExtras()); getFragmentManager() .beginTransaction() .add(R.id.fragment_container, firstFragment) .commit(); } } public void onArticleSelected(int position) { ArticleFragment articleFrag = (ArticleFragment) getFragmentManager() .findFragmentById(R.id.article_fragment); if (articleFrag != null) { articleFrag.updateArticleView(position); } else { ArticleFragment newFragment = new ArticleFragment(); Bundle args = new Bundle(); args.putInt(ArticleFragment.ARG_POSITION, position); newFragment.setArguments(args); getFragmentManager() .beginTransaction() .replace(R.id.fragment_container, newFragment) .addToBackStack(null) .commit(); } } }

自定義views

讓我們只使用views來重新實現上面代碼的相似版本。

首先,我們定義Container的概念,它可以顯示一個item,也可以處理返回鍵。

public interface Container { void showItem(String item); boolean onBackPressed(); }

Activity假設總會存在一個container,並把工作委託給它。

public class MainActivity extends Activity { private Container container; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_activity); container = (Container) findViewById(R.id.container); } public Container getContainer() { return container; } @Override public void onBackPressed() { boolean handled = container.onBackPressed(); if (!handled) { finish(); } } }

列表的代碼也類似如下:

public class ItemListView extends ListView { public ItemListView(Context context, AttributeSet attrs) { super(context, attrs); } @Override protected void onFinishInflate() { super.onFinishInflate(); final MyListAdapter adapter = new MyListAdapter(); setAdapter(adapter); setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { String item = adapter.getItem(position); MainActivity activity = (MainActivity) getContext(); Container container = activity.getContainer(); container.showItem(item); } }); } }

接著任務是:基於資源限定符載入不同的XML布局文件。

res/layout/main_activity.xml:

<com.squareup.view.SinglePaneContainer xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/container" > <com.squareup.view.ItemListView android:layout_width="match_parent" android:layout_height="match_parent" /> </com.squareup.view.SinglePaneContainer>

res/layout-land/main_activity.xml:

<com.squareup.view.DualPaneContainer xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" android:id="@+id/container" > <com.squareup.view.ItemListView android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="0.2" /> <include layout="@layout/detail" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="0.8" /> </com.squareup.view.DualPaneContainer>

下面是這些containers的簡單實現:

public class DualPaneContainer extends LinearLayout implements Container { private MyDetailView detailView; public DualPaneContainer(Context context, AttributeSet attrs) { super(context, attrs); } @Override protected void onFinishInflate() { super.onFinishInflate(); detailView = (MyDetailView) getChildAt(1); } public boolean onBackPressed() { return false; } @Override public void showItem(String item) { detailView.setItem(item); } }

public class SinglePaneContainer extends FrameLayout implements Container { private ItemListView listView; public SinglePaneContainer(Context context, AttributeSet attrs) { super(context, attrs); } @Override protected void onFinishInflate() { super.onFinishInflate(); listView = (ItemListView) getChildAt(0); } public boolean onBackPressed() { if (!listViewAttached()) { removeViewAt(0); addView(listView); return true; } return false; } @Override public void showItem(String item) { if (listViewAttached()) { removeViewAt(0); View.inflate(getContext(), R.layout.detail, this); } MyDetailView detailView = (MyDetailView) getChildAt(0); detailView.setItem(item); } private boolean listViewAttached() { return listView.getParent() != null; } }

抽象出這些container並以這種方式來構建app並不難-我們不僅不需要fragments,而且代碼將是易於理解的。

Views & presenters

使用自定義views是很棒的,但我們想把業務邏輯分離到專門的controllers中。我們把這些controller稱為presenters。這樣一來,代碼將更加可讀,測試更加容易。上面例子中的MyDetailView如下所示:

public class MyDetailView extends LinearLayout { TextView textView; DetailPresenter presenter; public MyDetailView(Context context, AttributeSet attrs) { super(context, attrs); presenter = new DetailPresenter(); } @Override protected void onFinishInflate() { super.onFinishInflate(); presenter.setView(this); textView = (TextView) findViewById(R.id.text); findViewById(R.id.button).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { presenter.buttonClicked(); } }); } public void setItem(String item) { textView.setText(item); } }

Ⅲ android fragment多窗口怎麼使用

、Fragment的產生與介紹

關於fragment的實例,請參考android學習手冊,android學習手冊包含9個章節,108個例子,源碼文檔隨便看,例子都是可交互,可運行,

源碼採用android studio目錄結構,高亮顯示代碼,文檔都採用文檔結構圖顯示,可以快速定位。360手機助手中下載,圖標上有貝殼。

Android運行在各種各樣的設備中,有小屏幕的手機,超大屏的平板甚至電視。針對屏幕尺寸的差距,很多情況下,都是先針對手機開發一套App,然後拷貝一份,修改布局以適應平板神馬超級大屏的。難道無法做到一個App可以同時適應手機和平板么,當然了,必須有啊。Fragment的出現就是為了解決這樣的問題。你可以把Fragment當成Activity的一個界面的一個組成部分,甚至Activity的界面可以完全有不同的Fragment組成,更帥氣的是Fragment擁有自己的生命周期和接收、處理用戶的事件,這樣就不必在Activity寫一堆控制項的事件處理的代碼了。更為重要的是,你可以動態的添加、替換和移除某個Fragment。

2、Fragment的生命周期


Fragment必須是依存與Activity而存在的,因此Activity的生命周期會直接影響到Fragment的生命周期。官網這張圖很好的說明了兩者生命周期的關系:


可以看到Fragment比Activity多了幾個額外的生命周期回調方法:
onAttach(Activity)
當Fragment與Activity發生關聯時調用。
onCreateView(LayoutInflater, ViewGroup,Bundle)
創建該Fragment的視圖
onActivityCreated(Bundle)
當Activity的onCreate方法返回時調用
onDestoryView()
與onCreateView想對應,當該Fragment的視圖被移除時調用
onDetach()
與onAttach相對應,當Fragment與Activity關聯被取消時調用
注意:除了onCreateView,其他的所有方法如果你重寫了,必須調用父類對於該方法的實現,

3、靜態的使用Fragment

嘿嘿,終於到使用的時刻了~~

這是使用Fragment最簡單的一種方式,把Fragment當成普通的控制項,直接寫在Activity的布局文件中。步驟:

1、繼承Fragment,重寫onCreateView決定Fragemnt的布局

2、在Activity中聲明此Fragment,就當和普通的View一樣

下面展示一個例子(我使用2個Fragment作為Activity的布局,一個Fragment用於標題布局,一個Fragment用於內容布局):

TitleFragment的布局文件:


[html] view plain print?

<?xmlversion="1.0"encoding="utf-8"?>

<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="match_parent"

android:layout_height="45dp"

android:background="@drawable/title_bar">

<ImageButton

android:id="@+id/id_title_left_btn"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_centerVertical="true"

android:layout_marginLeft="3dp"

android:background="@drawable/showleft_selector"/>

<TextView

android:layout_width="fill_parent"

android:layout_height="fill_parent"

android:gravity="center"

android:text="我不是微信"

android:textColor="#fff"

android:textSize="20sp"

android:textStyle="bold"/>

</RelativeLayout>

<?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="45dp"
android:background="@drawable/title_bar" >

<ImageButton
android:id="@+id/id_title_left_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="3dp"
android:background="@drawable/showleft_selector" />

<TextView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:text="我不是微信"
android:textColor="#fff"
android:textSize="20sp"
android:textStyle="bold" />

</RelativeLayout>

TitleFragment



[java] view plain print?

packagecom.zhy.zhy_fragments;

importandroid.app.Fragment;

importandroid.os.Bundle;

importandroid.view.LayoutInflater;

importandroid.view.View;

importandroid.view.View.OnClickListener;

importandroid.view.ViewGroup;

importandroid.widget.ImageButton;

importandroid.widget.Toast;

{

privateImageButtonmLeftMenu;

@Override

publicViewonCreateView(LayoutInflaterinflater,ViewGroupcontainer,

BundlesavedInstanceState)

{

Viewview=inflater.inflate(R.layout.fragment_title,container,false);

mLeftMenu=(ImageButton)view.findViewById(R.id.id_title_left_btn);

mLeftMenu.setOnClickListener(newOnClickListener()

{

@Override

publicvoidonClick(Viewv)

{

Toast.makeText(getActivity(),

"!",

Toast.LENGTH_SHORT).show();

}

});

returnview;

}

}

package com.zhy.zhy_fragments;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.Toast;

public class TitleFragment extends Fragment
{

private ImageButton mLeftMenu;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_title, container, false);
mLeftMenu = (ImageButton) view.findViewById(R.id.id_title_left_btn);
mLeftMenu.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
Toast.makeText(getActivity(),
"i am an ImageButton in TitleFragment ! ",
Toast.LENGTH_SHORT).show();
}
});
return view;
}
}


同理還有ContentFragment的其布局文件:



[html] view plain print?

<?xmlversion="1.0"encoding="utf-8"?>

<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:orientation="vertical">

<TextView

android:layout_width="fill_parent"

android:layout_height="fill_parent"

android:gravity="center"

android:text="使用Fragment做主面板"

android:textSize="20sp"

android:textStyle="bold"/>

</LinearLayout>

<?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:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:text="使用Fragment做主面板"
android:textSize="20sp"
android:textStyle="bold" />

</LinearLayout>

[java] view plain print?

packagecom.zhy.zhy_fragments;

importandroid.app.Fragment;

importandroid.os.Bundle;

importandroid.view.LayoutInflater;

importandroid.view.View;

importandroid.view.ViewGroup;

{

@Override

publicViewonCreateView(LayoutInflaterinflater,ViewGroupcontainer,

BundlesavedInstanceState)

{

returninflater.inflate(R.layout.fragment_content,container,false);

}

}

package com.zhy.zhy_fragments;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class ContentFragment extends Fragment
{

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
return inflater.inflate(R.layout.fragment_content, container, false);
}

}


MainActivity



[java] view plain print?

packagecom.zhy.zhy_fragments;

importandroid.app.Activity;

importandroid.os.Bundle;

importandroid.view.Window;

{

@Override

protectedvoidonCreate(BundlesavedInstanceState)

{

super.onCreate(savedInstanceState);

requestWindowFeature(Window.FEATURE_NO_TITLE);

setContentView(R.layout.activity_main);

}

}

package com.zhy.zhy_fragments;

import android.app.Activity;
import android.os.Bundle;
import android.view.Window;

public class MainActivity extends Activity
{

@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
}

}


Activity的布局文件:



[java] view plain print?

<RelativeLayoutxmlns: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">

<fragment

android:id="@+id/id_fragment_title"

android:name="com.zhy.zhy_fragments.TitleFragment"

android:layout_width="fill_parent"

android:layout_height="45dp"/>

<fragment

android:layout_below="@id/id_fragment_title"

android:id="@+id/id_fragment_content"

android:name="com.zhy.zhy_fragments.ContentFragment"

android:layout_width="fill_parent"

android:layout_height="fill_parent"/>

</RelativeLayout>

Ⅳ Android Fragment 開發框架合集

一個強大的 Fragment 管理框架,為"單 Activity + 多 Fragment ","多模塊 Activity + 多 Fragment "架構而生,簡化開發,輕松解決動畫、嵌套、事務相關等問題。

一個強大的Fragment管理框架。

這可能是使用成本最低的 Fragment 框架。
無需繼承!!!無需繼承!!!無需繼承!!! 重要的話說三遍!!
在使用 FragmentRigger 的時候,使用成本只有一絕指行註解!!!
原理: 是把 Fragment / Activity 生命周期相關方法定義為切點,通過 ASpectJ 綁定並使用代理類進行操作。

一個可以管理 Fragment 嵌套,狀態欄和 Toolbar 透明的庫。

可以能用構造一個 Activity 框架。

一個封裝了啟動模式的 Fragment 便捷使用庫,方便構建旁謹單 Activity + 多 Fragment 輕量級框架。

FragmentMaster 是一個庫,允許您輕松並啟配開發僅由 Fragments 導航的 Android 應用程序。

Fragmentation 可以使用介面實現Base類的方便擴展,功能也相當強大還支持 EventBus
FragmentRigger 使用了註解來實現框架,可能需要注意沖突
FragmentStack 相當輕量,適合比較簡單的需求使用

Ⅳ android 怎樣隱藏當前的fragement

解決方法 1:
您可以使用此方法要鎖定或解鎖抽屜: DrawerLayout.setDrawerLockMode(...) 。(也有兩個其他版本的此方法,以指定特定抽屜鎖模式)。若要鎖定,使用 DrawerLayout.LOCK_MODE_LOCKED_CLOSED ; 要解除鎖定,請使用DrawerLayout.LOCK_MODE_UNLOCKED 。
如果您正在使用 ActionBarDrawerToggle,您需要添加一些額外的代碼以防止抽屜打開時他們單擊 ActionBarDrawerToggle,如果你把鎖抽屜。
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// check lock mode before passing to ActionBarDrawerToggle
// I assume your drawer is on the left; if not, use Gravity.RIGHT
int lockMode = mDrawer.getDrawerLockMode(Gravity.LEFT);
if (lockMode == DrawerLayout.LOCK_MODE_UNLOCKED &&
mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle your other action bar items...

return super.onOptionsItemSelected(item);
}

Ⅵ android fragment和activity的區別

Fragment是到Android3.0+ 以後,Android新增了Fragments,在沒有 Fragment 之前,一個屏幕只能放一個 Activity。這是一個起源時間大家要知道是什麼時候開始引入的。
.Activity 代表了一個屏幕的主體,而Fragment可以作為Activity的一個組成元素。
一個Activity可以有若干個(0或n)Fragment構成。你可以把Fragment想像成Activity中的一個控制項,只不過相對於一般控制項,Fragment與Activity聯系更為緊密,隨著Activity的生命周期變化,Fragment也隨之相應不同的生命周期函數。
Fragment 從功能上講相當於一個子活動(Activity),它可以讓多個活動放到同一個屏幕上,也就是對用戶界面和功能的重用,因為對於大屏設備來說,純粹的 Activity 有些力不從心。
Fragment 像是一個子活動,但是 Fragment 不是 Activity 的擴展,因為 Fragment 擴展自 android.app 中的 Object,而 Activity 是 Context 的子類。Fragment 有自己的視圖層級結構,有自己的活動周期,還可以像活動一樣響應後退按鈕,Fragment 還有一個用作其初始化參數的包(Bundle),類似 Activity,Fragment 也可由系統自動保存並在以後還原。當系統還原 Fragment 時,它調用默認的構造函數(沒有參數),然後將此Bundle還原到新創建的 Fragment 中,所以無論新建還是還原 Fragment,都要經過兩個步驟:(1)調用默認構造函數(2)傳入新的或者保存起來的Bundle。
一個Activity可以運行多個 Fragment,Fragment 切換時,由 FragmentTransaction 執行,切換時,上一個 Fragment 可以保存在後退棧中(Back Stack),這里的後退棧由 FragmentManager 來管理,注意 Fragment 和 Activity 的後退棧是有區別的:Activity 的後退棧由系統管理,而 Fragment 的後退棧由所在的Activity 管理。
Fragment不能脫離Activity而存在,只有Activity才能作為接收intent的載體。其實兩者基本上是載體和組成元素的關系。
Fragment用來描述一些行為或一部分用戶界面在一個Activity中,你可以合並多個fragment在一個單獨的activity中建立多個UI面板,同時重用fragment在多個activity中.你可以認為fragment作為一個activity中的一節模塊,fragment有自己的生命周期,接收自己的輸入事件,你可以添加或移除從運行中的activity.一個fragment必須總是嵌入在一個activity中,同時fragment的生命周期受activity而影響,舉個例子吧,當activity暫停,那麼所有在這個activity的fragments將被destroy釋放。然而當一個activity在運行比如resume時,你可以單獨的操控每個fragment,比如添加或刪除。不過因為Fragment和Activity的生命周期都比較復雜,我們分別對比下:創建一個fragment你必須創建一個Fragment的子類或存在的子類,比如類似下面的代碼
public static class AndroidFragment extends Fragment{
@Override
public View onCreateView(LayoutInflaterinflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.android_fragment,container, false);
}
}

Fragment類的一些代碼看起來有些像Activity為了讓大家了解清楚,Android開發網給大家整理下 Fragment的生命周期大家可以參考一下網上關於生命周期的介紹 http://www.cnblogs.com/purediy/p/3276545.html,部分類似Activity的,我們詳細解釋
onCreate()
當fragment創建時被調用,你應該初始化一些實用的組件,比如在fragment暫停或停止時需要恢復的
onCreateView()
當系統調用fragment在首次繪制用戶界面時,如果畫一個UI在你的fragment你必須返回一個View當然了你可以返回null代表這個fragment沒有UI.
那麼如何添加一個Fragment到Activity中呢? Activity的布局可以這樣寫
<?xml version="1.0"encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment android:name="com.android.cwj.ArticleListFragment"
android:id="@+id/list"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent" />
<fragment android:name="com.android.cwj.ArticleReaderFragment"
android:id="@+id/viewer"
android:layout_weight="2"
android:layout_width="0dp"
android:layout_height="match_parent" />
</LinearLayout>

Ⅶ Android中Fragment怎樣刷新UI

在activity 的onActivityResult 調虛攜罩用fragment 的onActivityResult 方法隱汪,
例如getSupportFragmentManager().getFragments().get(mViewPager.getCurrentItem()).onActivityResult(requestCode, requestCode, data);
然差鬧後在fragment的onActivityResult做處理

Ⅷ android fragment有什麼用

自從Android 3.0中引入fragments 的概念,其目的是為了解決不同屏幕分辯率的動態和靈活UI設計。大屏幕如平板小屏幕如手機,平板電腦的設計使得其有更多的空間來放更多的UI組件,而多出來的空間存放UI使其會產生更多的交互,從而誕生了fragments 。
fragments 的設計不需要你來親自管理view hierarchy 的復雜變化,通過將Activity 的布局分散到frament 中,可以在運行時修改activity 的外觀,並且由activity 管理的back stack 中保存些變化。當一個片段指定了自身的布局時,它能和其他片段配置成不同的組合,在活動中為不同的屏幕尺寸修改布局配置(小屏幕可能每次顯示一個片段,而大屏幕則可以顯示兩個或更多)。
ITjob網有關於Android的文章和帖子,如果你想了解的更細致的話,可以自己去看看。也可以去相關的論壇,或者大牛的博客看看。希望對你有幫助。

閱讀全文

與androidfragments相關的資料

熱點內容
2019中日韓免費好看的電影 瀏覽:660
雲伺服器怎麼綁定亞馬遜 瀏覽:852
怎樣破解網盤加密資源 瀏覽:86
青瓷pdf 瀏覽:425
壓縮空氣一立方米耗電多少 瀏覽:458
釘盤文件夾名 瀏覽:290
22dyorg /info /393348.html 瀏覽:962
顧念的小說免費閱讀 瀏覽:784
岳雲鵬過安檢掉東西的電影叫什麼 瀏覽:786
泰國大尺度同性戀 瀏覽:169
馬小樂第二部全集目錄 瀏覽:167
電影女主角叫安吉電影的名字 瀏覽:713
怎麼樣加密網站 瀏覽:306
psql命令q 瀏覽:722
日本觀影網址 瀏覽:471
百萬英鎊電影下載英文 瀏覽:617
迷案記《招魂的童謠》 瀏覽:400
java線程怎麼用 瀏覽:968
看大尺度電影在哪看 瀏覽:545
泰國人妖電影。 瀏覽:697