Android-fragment簡介-fragment的簡單使用

1.fragment簡介

   在Android3.0版本以前Google尚未推出fragment,在Android3.0版本以後Google推出了fragment,因爲Android3.0版本是過渡期版本,fragment真正大量使用是在Android4.0版本以後,已經有了Activity爲何Google還有設計出fragment呢,是由於以前的Android版本一直是爲手機考慮,後來慢慢的就決定要多設備發展(例如:平板)因此有了fragment的出現

    fragment是一個特殊的控件,fragment是有生命週期的控件,fragment必須在Activity之上運行(意思就是:fragment是被Activity定義和控制的)能夠對 fragment 添加、移除、管理 等操做android

 

  Activity / Fragment開發過程當中的比較:app

  

  

    能夠理解爲:Fragment的出現能夠分離Activity代碼

 


 

2.案例:簡單的 Fragment Demo

 MyTestFragmentActivity

package liudeli.activity.fragment;

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

import liudeli.activity.R;

public class MyTestFragmentActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_test_fragment);
    }
}

 

 MyTestFragmentActivity 的 佈局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <!--
        android:id="@+id/fragment" 必需要指定好ID,不然運行會報錯
        class="liudeli.activity.fragment.MyFragment" 必需要指定class,不然無效果
    -->
    <fragment
        android:id="@+id/fragment"
        class="liudeli.activity.fragment.MyFragment"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

 

 佈局 <fragment class 引用的  MyFragment

package liudeli.activity.fragment;

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

public class MyFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        TextView textView = new TextView(getActivity()); // 不能使用this,由於Fragment父類不是Context
        textView.setText("我是MyFragment");

        /* 也能夠是使用佈局加載器加載
        View view = inflater.inflate(R.layout.xxx, null);
        view.findViewById(R.id.xxx);
        view.findViewById(R.id.xxx);
        .....
        */
        return textView;
    }
}

 

 效果:ide

相關文章
相關標籤/搜索