Android Fragment 簡單一實例

來源:互聯網
上載者:User

標籤:android   fragment   android片段   

  Android上的介面展示都是通過Activity實現的,Activity實在是太常用了,我相信大家都已經非常熟悉了,這裡就不再贅述。 但是Activity也有它的局限性,同樣的介面在手機上顯示可能很好看,在平板上就未必了,因為平板的螢幕非常大,手機的介面放在平板上可能會有過分被拉長、控制項間距過大等情況。這個時候更好的體驗效果是在Activity中嵌入”小Activity”,然後每個”小Activity”又可以擁有自己的布局。這就是Fragment片段技術。

一、Fragment簡介

  Android是在Android 3.0 (API level 11)開始引入Fragment的。可以把Fragment想成Activity中的模組,這個模組有自己的布局,有自己的生命週期,單獨處理自己的輸入,在Activity啟動並執行時候可以載入或者移除Fragment模組。可以把Fragment設計成可以在多個Activity中複用的模組。當開發的應用程式同時適用於平板電腦和手機時,可以利用Fragment實現靈活的布局,改善使用者體驗。

二、Fragment生命週期

  因為Fragment必須嵌入在Acitivity中使用,所以Fragment的生命週期和它所在的Activity是密切相關的。
  如果Activity是暫停狀態,其中所有的Fragment都是暫停狀態;如果Activity是stopped狀態,這個Activity中所有的Fragment都不能被啟動;如果Activity被銷毀,那麼它其中的所有Fragment都會被銷毀。但是,當Activity在活動狀態,可以獨立控制Fragment的狀態,比如加上或者移除Fragment。
  當這樣進行fragment transaction(轉換)的時候,可以把fragment放入Activity的back stack中,這樣使用者就可以進行返回操作。
  
  Activity與Fragment生命週期對比圖
  

三、兩個簡單一實例
  1. 簡單的Fragment練習,Activity與Fragment通訊

    布局檔案activity_main.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"    tools:context=".MainActivity" >    <FrameLayout        android:layout_weight="1"        android:id="@+id/content"        android:layout_width="wrap_content"        android:layout_height="0dp" >    </FrameLayout>    <android.support.v4.app.FragmentTabHost        android:id="@+id/tab"        android:layout_width="fill_parent"        android:layout_height="wrap_content" /></LinearLayout>

Java檔案

package com.example.fragmenttabhost;import android.os.Bundle;import android.support.v4.app.ListFragment;import android.widget.ArrayAdapter;import android.widget.Toast;public class MyFragment extends ListFragment{    String show1[] = {"1.1","1.2","1.3","1.4"};    String show2[] = {"2.1","2.2","2.3","2.4"};    @Override    public void onActivityCreated(Bundle savedInstanceState) {        super.onActivityCreated(savedInstanceState);        String show[] = null;        Bundle bundle = getArguments();        if(bundle == null)            show = show1;        else {            show = show2;            Toast.makeText(getActivity(), (CharSequence) bundle.get("key"), 1).show();        }        setListAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, show));    }}
package com.example.fragmenttabhost;import android.os.Bundle;import android.support.v4.app.FragmentActivity;import android.support.v4.app.FragmentTabHost;public class MainActivity extends FragmentActivity {    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        FragmentTabHost tabHost = (FragmentTabHost) findViewById(R.id.tab);        tabHost.setup(this, getSupportFragmentManager(), R.id.content);        tabHost.addTab(tabHost.newTabSpec("tab1").setIndicator("Tab1"), MyFragment.class, null);        Bundle b = new Bundle();        b.putString("key", "I am tab2");        tabHost.addTab(tabHost.newTabSpec("tab2").setIndicator("Tab2",getResources().getDrawable(R.drawable.ic_launcher)), MyFragment.class, b);    }}

運行結果


2. 比較好看的demo,模仿首頁面

片段布局檔案fragment_1,2,3,4,5.xml

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="fill_parent" >    <ImageView        android:id="@+id/imageview"        android:layout_width="fill_parent"        android:layout_height="fill_parent"        android:scaleType="fitCenter"        android:src="@drawable/mm1" >    </ImageView></LinearLayout>

tab_item_view.xml按鈕布局

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:gravity="center"    android:orientation="vertical" >    <ImageView        android:id="@+id/imageview"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:focusable="false"        android:padding="3dp"         android:src="@drawable/tab_home_btn">    </ImageView>    <TextView        android:id="@+id/textview"               android:layout_width="wrap_content"        android:layout_height="wrap_content"         android:text="首頁"        android:textSize="10sp"        android:textColor="#ffffff">    </TextView></LinearLayout>

首頁面布局main_tab_layout.xml

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:orientation="vertical" >    <FrameLayout        android:id="@+id/realtabcontent"        android:layout_width="fill_parent"        android:layout_height="0dip"        android:layout_weight="1" />    <android.support.v4.app.FragmentTabHost        android:id="@android:id/tabhost"        android:layout_width="fill_parent"        android:layout_height="wrap_content"         android:background="@drawable/maintab_toolbar_bg">        <FrameLayout            android:id="@android:id/tabcontent"            android:layout_width="0dp"            android:layout_height="0dp"            android:layout_weight="0" />                </android.support.v4.app.FragmentTabHost></LinearLayout>

FragmentPage1,2,3,4,5.java片段實現

package com.vhreal.myfragmenttest;import com.vhreal.myfragmenttest.R;import android.os.Bundle;import android.support.v4.app.Fragment;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;public class FragmentPage1 extends Fragment{    @Override    public View onCreateView(LayoutInflater inflater, ViewGroup container,            Bundle savedInstanceState) {        return inflater.inflate(R.layout.fragment_1, null);         }   }

首頁面實現MainTabActivity.java

package com.vhreal.myfragmenttest;import com.vhreal.myfragmenttest.R;import android.os.Bundle;import android.support.v4.app.FragmentActivity;import android.support.v4.app.FragmentTabHost;import android.view.LayoutInflater;import android.view.View;import android.widget.ImageView;import android.widget.TabHost.TabSpec;import android.widget.TextView;/** * @author vhreal * 功能描述:自訂TabHost */public class MainTabActivity extends FragmentActivity {    // 定義FragmentTabHost對象    private FragmentTabHost mTabHost;    // 定義一個布局    private LayoutInflater layoutInflater;    // 定義數組來存放Fragment介面    private Class fragmentArray[] = { FragmentPage1.class, FragmentPage2.class,            FragmentPage3.class, FragmentPage4.class, FragmentPage5.class };    // 定義數組來存放按鈕圖片    private int mImageViewArray[] = { R.drawable.tab_home_btn,            R.drawable.tab_message_btn, R.drawable.tab_selfinfo_btn,            R.drawable.tab_square_btn, R.drawable.tab_more_btn };    // Tab選項卡的文字    private String mTextviewArray[] = { "首頁", "訊息", "好友", "廣場", "更多" };    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main_tab_layout);        initView();    }    /**     * 初始化組件     */    private void initView() {        // 執行個體化布局對象        layoutInflater = LayoutInflater.from(this);        // 執行個體化TabHost對象,得到TabHost        mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);        mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);        // 得到fragment的個數        int count = fragmentArray.length;        for (int i = 0; i < count; i++) {            // 為每一個Tab按鈕設定表徵圖、文字和內容            TabSpec tabSpec = mTabHost.newTabSpec(mTextviewArray[i])                    .setIndicator(getTabItemView(i));            // 將Tab按鈕添加進Tab選項卡中            mTabHost.addTab(tabSpec, fragmentArray[i], null);            // 設定Tab按鈕的背景            mTabHost.getTabWidget().getChildAt(i)                    .setBackgroundResource(R.drawable.selector_tab_background);        }    }    /**     * 給Tab按鈕設定表徵圖和文字     */    private View getTabItemView(int index) {        View view = layoutInflater.inflate(R.layout.tab_item_view, null);        ImageView imageView = (ImageView) view.findViewById(R.id.imageview);        imageView.setImageResource(mImageViewArray[index]);        TextView textView = (TextView) view.findViewById(R.id.textview);        textView.setText(mTextviewArray[index]);        return view;    }}

運行結果

四、參考引用
  • android片段Fragment簡介詳解
  • Android Fragment 基本介紹
  • Android Fragment 真正的完全解析(上下)必看

Android Fragment 簡單一實例

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.