1. 程式人生 > >Fragment 詳細介紹(由來、靜態載入,動態載入,頁卡滑動切換)

Fragment 詳細介紹(由來、靜態載入,動態載入,頁卡滑動切換)

1.什麼是Fragment?

Fragment的由來

基於Android系統的裝置越來越多,解析度種類越來越多,Google提出Fragment的概念也是希望通過Fragment解決螢幕碎片化問題。

Fragment的翻譯為碎片,自Android3.0開始引入Fragment的概念

用Fragment替換TabHost是Google推薦的方案

2.Fragment 能夠比之前v4 有什麼好處呢?

1,使用Fragment可以在一個Activity中實現不同介面的靈活切換

2,Fragment解決了Activity間的切換不流暢,佈局切換更輕量

3,Fragment可以封裝成不同的重要元件,並可以

單獨管理其生命週期和UI佈局。

4,Fragment無需在AndroidManifest中註冊,可以在佈局檔案中直接引用

3,Fragment靜態載入方法(步驟)

  •     新建類繼承Fragment;
  •     重寫onCreateView方法;
  •     使用LayoutInflater物件中的inflate方法繫結佈局和控制元件;
  •     在Activity對應的佈局檔案中通過<fragment>標籤引用。       

新建一個專案,再裡面新建Fragment extends Fragment 

程式碼如下:

public class BlankFragment extends Fragment {


    public BlankFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view=inflater.inflate(R.layout.fragment_blank, container, false);

        return view;

它的xml 程式碼如下:

<FrameLayout 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.xdw.myapplication.BlankFragment">

    <!-- TODO: Update blank fragment layout -->
<TextView
    android:id="@+id/fragment_textview"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:text="這是一個FragmentA"
    android:gravity="center"
    android:background="#101fc2"
    android:textColor="#000000"
    android:textSize="35dp"
    />

</FrameLayout>

XML效果圖:

在acticity_main.xml 裡 出除了新增一個TextView,還要新增fragment    裡面最重要的屬性就是 id   和   name   ,程式碼如下:

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

    <TextView
        android:id="@+id/main_textview"
        android:layout_width="match_parent"
        android:layout_height="150dp"
        android:text="這是一個TextView"
        android:gravity="center"
        />
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    >
    <fragment
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="match_parent"
        android:id="@+id/fragment_one"
        android:name="com.xdw.myapplication.BlankFragment"

        />

</LinearLayout>


</LinearLayout>

xml效果圖:


執行出來的效果圖:


4,Fragment 動態載入:

  • 新建類繼承Fragment
  • 重寫onGreateView方法
  • 使用layout infler 物件中的inflate 方法繫結佈局和控制元件
  • 使用FragmentManger FragmentTransaction 物件進行動態載入

程式碼如下:

package com.xdw.myapplication;

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.Button;

import com.xdw.myapplication.fragment.NanFragment;
import com.xdw.myapplication.fragment.NvFragment;

public class TianMaoActivity extends AppCompatActivity implements View.OnClickListener{
private Button nan_btn;
private Button nv_btn;
private NanFragment nanFragment;
private NvFragment nvFragment;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tian_mao);
       bindID();


    }

    private void bindID() {
        nan_btn=findViewById(R.id.nan_btn);
        nv_btn=findViewById(R.id.nv_btn);

        nan_btn.setOnClickListener(this);
        nv_btn.setOnClickListener(this);

    }

    @Override
    public void onClick(View view) {
        FragmentManager manager=getFragmentManager();//建立FragmentManger物件   (管理器)
        FragmentTransaction transaction=manager.beginTransaction();//建立FragmentTransaction物件
        // 事務物件 對Fragment進行新增,移除,替換,提交等操作
        switch (view.getId()){
            case R.id.nan_btn:
                if(nanFragment==null){
                    //顯示男裝
                    nanFragment =new  NanFragment();
                }
                    transaction.replace(R.id.shop_framelayout,nanFragment);
                break;
            case R.id.nv_btn:
                if (nvFragment==null){
                    //顯示女裝
                    nvFragment =new NvFragment();
                }
                transaction.replace(R.id.shop_framelayout,nvFragment);
               break;
               default:
                   break;

        }

        transaction.commit();//提交
    }
}

xml程式碼如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    tools:context="com.xdw.myapplication.TianMaoActivity">

  <LinearLayout
      android:layout_width="100dp"
      android:layout_height="match_parent"
      android:orientation="vertical"
      >
      <Button
          android:layout_marginTop="50dp"
          android:id="@+id/nan_btn"
          android:layout_width="match_parent"
          android:layout_height="50dp"
          android:text="男裝"

          />
      <Button
          android:layout_marginTop="50dp"
          android:id="@+id/nv_btn"
          android:layout_width="match_parent"
          android:layout_height="50dp"
          android:text="女裝"

          />


  </LinearLayout>
    <FrameLayout
        android:id="@+id/shop_framelayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    </FrameLayout>

</LinearLayout>

效果如圖


5,實現頁卡切換效果:

程式碼如下:

package com.xdw.myapplication;

import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import com.xdw.myapplication.adaper.MyPageAdaper;
import com.xdw.myapplication.fragment.FriendFragment;
import com.xdw.myapplication.fragment.NewsFragment;
import com.xdw.myapplication.fragment.PlayFragment;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button btn_friend;
private Button btn_news;
private Button btn_play;
private FriendFragment friendFragment;
private NewsFragment   newsFragment;
private PlayFragment   playFragment;
private ViewPager viewPager;
private List<Fragment>   fragmentList=new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        bindID();
        friendFragment =new FriendFragment();
        newsFragment =new NewsFragment();
        playFragment =new PlayFragment();
        fragmentList.add(friendFragment);
        fragmentList.add(newsFragment);
        fragmentList.add(playFragment);

        MyPageAdaper adaper=new MyPageAdaper(getSupportFragmentManager(),fragmentList);
        viewPager.setAdapter(adaper);

    }

    private void bindID() {
        btn_friend=findViewById(R.id.main_friend);
        btn_news=findViewById(R.id.main_news);
        btn_play=findViewById(R.id.main_play);
        viewPager=findViewById(R.id.main_viewpager);
        btn_friend.setOnClickListener(this);
        btn_play.setOnClickListener(this);
        btn_news.setOnClickListener(this);

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case  R.id.main_friend:
                viewPager.setCurrentItem(0);
                break;
            case  R.id.main_news:
                viewPager.setCurrentItem(1);
                break;
            case  R.id.main_play:
                viewPager.setCurrentItem(2);
                break;
                default:
                    break;
        }
    }
}

adaper 程式碼如下:
package com.xdw.myapplication.adaper;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

import java.util.List;

/**
 * Created by lenovo on 2018/3/6.
 */

public class MyPageAdaper extends FragmentPagerAdapter {

    private List<Fragment> mfragmentlist;

    public MyPageAdaper(FragmentManager fm, List<Fragment> fragmentList) {
        super(fm);
        this.mfragmentlist=fragmentList;
    }

    @Override
    public Fragment getItem(int position) {
        return mfragmentlist.get(position);
    }

    @Override
    public int getCount() {
        return mfragmentlist.size();
    }
}


在activity_main.xml裡  

程式碼如下:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.xdw.myapplication.MainActivity">
<LinearLayout
    android:id="@+id/main_btn"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:orientation="horizontal"
    android:layout_alignParentBottom="true"
    >
    <Button
        android:id="@+id/main_friend"
        android:layout_width="0dp"
        android:layout_height="50dp"
        android:layout_weight="1"
        android:text="朋友圈"
        />
    <Button
        android:id="@+id/main_news"
        android:layout_width="0dp"
        android:layout_height="50dp"
        android:layout_weight="1"
        android:text="訊息"
        />
    <Button
        android:id="@+id/main_play"
        android:layout_width="0dp"
        android:layout_height="50dp"
        android:layout_weight="1"
        android:text="動態"
        />

</LinearLayout>
    <android.support.v4.view.ViewPager
        android:id="@+id/main_viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/main_btn"
        >
    </android.support.v4.view.ViewPager>


</RelativeLayout>

效果如圖:


希望給大家帶來幫助

相關推薦

Fragment 詳細介紹由來靜態載入動態載入滑動切換

1.什麼是Fragment? Fragment的由來 基於Android系統的裝置越來越多,解析度種類越來越多,Google提出Fragment的概念也是希望通過Fragment解決螢幕碎片化問題。 Fragment的翻譯為碎片,自Android3.0開始引入Fragmen

JAVA多執行緒:Thread API詳細介紹 sleepInterruptJoinTimeUnityieldinterrupted執行緒優先順序

 本章深入分析了Thread的所有API,熟練掌握Thread的API是學好Thread的前提。   執行緒sleep sleep是一個靜態方法,一共有兩個過載方法,一個需要傳入毫秒數,另一個既要傳入毫秒數又要傳入納秒數。   sleep方法介紹

[轉]Xilinx Vivado的使用詳細介紹1:創建工程編寫代碼行為仿真Testbench

always 選擇器 資料 多個 sign bench 通過 output tar 新建工程 打開Vivado軟件,直接在歡迎界面點擊Create New Project,或在開始菜單中選擇File - New Project即可新建工程。 點擊Next 輸入工程名稱和

Python--列表list元組(tuple)字典dict 詳細介紹1

在此中介紹列表(list)、元組(tuple)、字典(dict)的使用方法 檢視方法:Ctrl+Q ( 關鍵字、函式和方法的特點和區別: 關鍵字 是Python內建的、具有特殊意義的識別符號   (關鍵字後面不需要使用括號) 函式  封裝了獨立功能,可以直接呼叫  

PHP操作MongoDB資料庫詳細例子介紹

PHP操作mongodb:PHP 要操作mongodb需要打模組官網可以下載:http://pecl.php.net/package/mongo 下載mongodb設定成使用者授權的啟動方式php手冊沒有些使用者授權方式登陸的方法:conn.php<?php$conn = new Mongo("mong

thinkPHP 空模組和空操作前置操作和後置操作 詳細介紹十四

一、空模組和空操作1、空操作function _empty($name){$this->show("$name 不存在 <a href='__APP__/Index/index'>返回首頁</a>");}2.空模組(EmptyAction.class.php的檔案)class E

Xilinx Vivado的使用詳細介紹2:綜合實現管腳分配時鐘設定燒寫

前面一篇介紹了從新建工程一直到編寫程式碼進行行為模擬,這篇繼續進行介紹。 修改器件型號 新建工程時選擇過器件型號,如果新建好工程後需要修改型號,可以選擇選單Tools - Project Settings。 彈出視窗中,點選Project Device右側的按鈕

Android-Fragment基本知識靜態載入動態載入

1.回顧    上篇瞭解了和學習了 Andorid 的webView 的使用 2.重點    (1)Fragment基本知識    (2)Fragment 靜態載入    (3)Fragment 動態

分布式一致性協議介紹PaxosRaft

設置 -s ssi 選擇 參與 follow 初始 red 但是 兩階段提交 Two-phase Commit(2PC):保證一個事務跨越多個節點時保持 ACID 特性; 兩類節點:協調者(Coordinator)和參與者(Participants),協調者只有一個,參與

思科項目1實戰vlan靜態單臂浮動路由vrrp/standbynat端口映射遠程等)

vlan vrrp 單臂路由 nat pc配地址:C1192.168.10.10192.168.10.1C2192.168.20.10192.168.20.1C3192.168.10.20192.168.10.1C4192.168.20.20192.168.20.1需求1:SW1(config

Xilinx Vivado的使用詳細介紹5:調用用戶自定義封裝的IP核

cond 5.4 vba adding 計算機 property with 我們 class Zedboard OLED Display Controller IP v1 介紹

微信小程式-微信支付詳細介紹Thinkphp後端程式碼

流程 如微信支付的文件,不再多說 https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=7_4&index=3 一一分析一下每一步我們具體要做什麼: 1、小程式內呼叫登入介面,獲取到使用者的o

display:box佈局的詳細介紹圖解

使用display:-webkit-box佈局很久了,但是每次使用的時候都是現用現查,而且發現網上沒有找到一篇非常全面的關於此佈局的介紹,今天決定寫一篇部落格來記錄這個自適應佈局。 1、首先不同的瀏覽器要做不同的相容:目前box-flex屬性還沒有得到firefox、Opera、chrome瀏覽

帶你瞭解什麼是Activiti工作流Activiti工作流資料庫表詳細介紹23張表

帶你五分鐘瞭解工作流 什麼是工作流 說到工作流,一圖勝萬言。 工作流 Georgakopoulos給出的工作流定義是:工作流是將一組任務組織起來以完成某個經營過程:定義了任務的觸發順序和觸發條件,每個任務可以由一個或多個軟體系統完成,也可以由一個或一組人完成,還可以由一個或多個

靜態連結庫LIB動態連結庫DLLDLL的靜態載入動態載入兩種LIB檔案。

靜態連結庫(LIB)和動態連結庫(DLL),DLL的靜態載入和動態載入,兩種LIB檔案。 一、 靜態連結庫(LIB,也簡稱“靜態庫”)與動態連結庫(DLL,也簡稱“動態庫”)的區別 靜態連結庫與動態連結庫都是共享程式碼的方式,如果採用靜態連結庫,則無論你願不願意,lib 中的指令都全部被直接包含在最

ILSVRC競賽詳細介紹ImageNet Large Scale Visual Recognition Challenge

ILSVRC(ImageNet Large Scale Visual Recognition Challenge)是近年來機器視覺領域最受追捧也是最具權威的學術競賽之一,代表了影象領域的最高水平。 ImageNet資料集是ILSVRC競賽使用的是資料集,由斯坦福大學李飛飛教授主導,包含了超過14

將python打包成exe檔案詳細介紹各種坑解決

安裝pyinstaller 一開始偷懶,直接使用的pip安裝,結果各種問題 pip install pyinstaller 所以還是去github去下載最新的pyinstaller,替換掉用pip安裝好的pyinstaller,下載連結:pyinstall

Xilinx Vivado的使用詳細介紹3:使用IP核

ilinx Vivado的使用詳細介紹(3):使用IP核 Author:zhangxianhe IP核(IP Core) Vivado中有很多IP核可以直接使用,例如數學運算(乘法器、除法器、浮點運算器等)、訊號處理(FFT、DFT、DDS等)。IP核類似程式設計中的函式庫(例如C語言中的printf()

Xilinx Vivado的使用詳細介紹4:Zedboard+vivado之流水燈加SDK

Vivado+zedboard之初學流水燈 Author:zhangxianhe 環境:vivado 2016.3(已驗證適用於2015.4) 開發板:Zedboard version xc7z020clg484-1 實驗:使用Vivado和SDK進行Zedboard開發,製作一個簡單的流水燈程式以說明軟硬體

Xilinx Vivado的使用詳細介紹5:呼叫使用者自定義封裝的IP核

Zedboard OLED Display Controller IP v1 介紹