Android Fragment

Similar documents
主程式 : public class Main3Activity extends AppCompatActivity { ListView listview; // 先整理資料來源,listitem.xml 需要傳入三種資料 : 圖片 狗狗名字 狗狗生日 // 狗狗圖片 int[] pic =new

多媒體應用 13 新增專案並完成版面配置 <ExMusic01> <activity_main.xml> ImageView ID imgplay ImageView ID imgstop ImageView ID imgfront TextView ID txtsong TextView ID t

Android Service

Dynamic Layout in Android

res/layout 目录下的 main.xml 源码 : <?xml version="1.0" encoding="utf 8"?> <TabHost android:layout_height="fill_parent" xml

RecyclerView and CardVew

單步除錯 (1/10) 打開 Android Studio, 點選 Start a new Android Studio project 建立專案 Application name 輸入 BMI 點下 Next 2 P a g e

预览图 : (2) 在 SelectCity.java 中增加控件, 用于绑定 select_city 文件的 ListView, TextView,EditTest 等控件 代码和注释如下 :

Android + NFC

實作SQLiteOpenHelper類別

詞 彙 表 編 號 詞 彙 描 述 1 預 約 人 資 料 中 文 姓 名 英 文 姓 名 身 份 證 字 號 預 約 人 電 話 性 別 2 付 款 資 料 信 用 卡 別 信 用 卡 號 信 用 卡 有 效 日 期 3 住 房 條 件 入 住 日 期 退 房 日 期 人 數 房 間 數 量 入

用手機直接傳值不透過網頁連接, 來當作搖控器控制家電 ( 電視遙控器 ) 按下按鍵發送同時會回傳值來確定是否有送出 問題 :1. 應該是使用了太多 thread 導致在傳值上有問題 2. 一次按很多次按鈕沒辦法即時反應

建立Android新專案

Android 编程基础 Android 开发教程 & 笔记 1

建模与图形思考

untitled

Microsoft Word - weather12 刷新按钮动画+搜索框+bug处理.docx

Microsoft Word - 01.DOC

建立Android新專案

EJB-Programming-4-cn.doc

图 6-1 主界面 MainActivity 界面对应的布局文件 (activity_main.xml) 如下所示 : <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="

0511-Android程式之GPS應用_專題週記4

建模与图形思考

untitled

Chapter 1: Introduction

Java

《大话设计模式》第一章

PowerPoint 簡報

幻灯片 1

Microsoft Word - 第4章 3D相册.doc

Chapter 10

投影片 1

Android + WebService

Android 开发教程

Android 开发教程

<android.support.v7.widget.recyclerview android:layout_width="0dp" android:layout_height="0dp" android:layout_marginbottom

untitled

单击以编辑母片 Content 标题样式 LinearLayout 排版模式 TableLayout 排版模式 RelativeLayout 排版模式 AbsoluteLayout 排版模式 FrameLayout 排版模式 GridLayout 排版模式 TabWidget 切換卡 Lab 5 2

<4D F736F F F696E74202D20332D322E432B2BC3E6CFF2B6D4CFF3B3CCD0F2C9E8BCC6A1AAD6D8D4D8A1A2BCCCB3D0A1A2B6E0CCACBACDBEDBBACF2E707074>

Microsoft Word - ch04三校.doc

Android Android Android SDK iv

(TestFailure) JUnit Framework AssertionFailedError JUnit Composite TestSuite Test TestSuite run() run() JUnit

新版 明解C++入門編

Microsoft Word - 第3章.doc

EJB-Programming-3.PDF

Microsoft Word - AEL CH05.doc

Lecture01_Android介绍

任务实施 (1) 创建项目 图 3-1 欢迎界面 首先创建一个工程, 将其命名为 BoXueGu, 指定包名为 com.boxuegu (2) 导入界面图片将欢迎界面所需要的背景图片 launch_bg.png 导入到 drawable 文件夹中, 项目的 icon 图标 app_icon.png

使 用 Java 语 言 模 拟 保 险 箱 容 量 门 板 厚 度 箱 体 厚 度 属 性 锁 具 类 型 开 保 险 箱 关 保 险 箱 动 作 存 取 款

建立Android新專案

OOP with Java 通知 Project 4: 4 月 18 日晚 9 点 关于抄袭 没有分数

全国计算机技术与软件专业技术资格(水平)考试

Microsoft Word - 第3章.doc

INTRODUCTION TO COM.DOC

CC213

06 01 action JavaScript action jquery jquery AJAX CSS jquery CSS jquery HTML CSS jquery.css() getter setter.css('backgroundcolor') jquery CSS b

前言 C# C# C# C C# C# C# C# C# microservices C# More Effective C# More Effective C# C# C# C# Effective C# 50 C# C# 7 Effective vii

Chapter 1: Introduction

第一章 Android 简介与开发环境搭建

Lecture01_Android介绍

Microsoft Word - 02.目錄.doc

「西醫基層總額支付委員會《第28次委員會議紀錄


Microsoft PowerPoint - ch6 [相容模式]

書面

Microsoft Word - 第3章.doc

FY.DOC

内文-2.indd

JavaIO.PDF

<ADB6ADB1C25EA8FAA6DB2D4D56432E706466>

任務二 : 產生 20 個有炸彈的磚塊, 放在隨機的位置編輯 Block 類別的程式碼 import greenfoot.; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) Write a description of class

untitled

<4D F736F F D20C8EDC9E82DCFC2CEE7CCE22D3039C9CF>

% % 43.13% % % % %

Strings

投影片 1

使用MapReduce读取XML文件

FIT1改1.FIT)

KillTest 质量更高 服务更好 学习资料 半年免费更新服务

Chapter 9: Objects and Classes

Information for consent

移动平台期末展示

Microsoft Word - 第3章 Activity.doc

1 Framework.NET Framework Microsoft Windows.NET Framework.NET Framework NOTE.NET NET Framework.NET Framework 2.0 ( 3 ).NET Framework 2.0.NET F

基于ECO的UML模型驱动的数据库应用开发1.doc

untitled

untitled

概述

OOP with Java 通知 Project 4: 4 月 19 日晚 9 点

javaexample-02.pdf

Chapter 4

運算子多載 Operator Overloading

Microsoft Word - MIS.doc

威 福 髮 藝 店 桃 園 市 蘆 竹 區 中 山 里 福 祿 一 街 48 號 地 下 一 樓 50,000 獨 資 李 依 純 105/04/06 府 經 登 字 第 號 宏 品 餐 飲 桃 園 市 桃 園 區 信 光 里 民

國立臺東高級中學102學年度第一學期第二次期中考高一國文科試題

Microsoft Word - Sunday

鎶ョ焊0

!! :!!??!!?!??!!!... :... :'?'?! :' ' :'?' :'?' :'!' : :? Page 2

Page 2 of 12

Transcription:

Android Fragment 建國科技大學資管系饒瑞佶 2017/10 V1

Android 3.0 後才支援 Fragment 解決部分 App 適應螢幕大小的問題 它類似於 Activity, 可以像 Activity 可以擁有自己的版面設計, 也和 Activity 一樣有自己的生命週期 ( 具備 oncreate() oncreateview() 與 onpause() 方法 )

LifeCycle 圖片來源 : https://stackoverflow.com/questions/36339811/w hen-is-onattach-called-during-the-fragmentlifecycle

Fragment 特點 螢幕上同時間只能出現一個 Activity, 但卻可以出現多個 Fragment Fragment 有自己的 layout 與事件 ( 跟 Activity 一樣 ) 只是 Fragment 無法單獨存在, 它必須依附在 Activity 下 Fragment 可以動態被加入 Activity 或從 Activity 移除, 因此可以做到手機和平板有不同的顯示方式

Activity 加入 Fragment 方法 1: 直接在 layout 中使用 <fragment> 加入 方法 2: 透過程式, 使用 FragmentTransaction 類別, 指定 fragment 要加入到哪個 ViewGroup 內

方法 1 直接在 layout 中使用 <fragment> 加入

建立 fragment_1.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:background="#ff00ff" > <TextView android:id="@+id/text_view" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text=" 我是 fragment1" android:textsize="30sp"/> </LinearLayout>

建立 Fragment_1.java 只建立 oncreateview 就可以 繼承自 class Fragment Fragment 自己的 layout

@TargetApi(Build.VERSION_CODES.HONEYCOMB) public class Fragment_1 extends Fragment { @Override public View oncreateview(layoutinflater inflater, ViewGroup container, Bundle savedinstancestate) { return inflater.inflate(r.layout.fragment_1, container, false); } }

建立主畫面 usefragment.xml <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:id="@+id/fragment1" android:name="tw.edu.ctu.imetest.myapplication.fragment_1" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" /> </LinearLayout> 載入對應的 Fragment class

方法 2 使用 FragmentTransaction 類別

作法 首先建立主畫面 fragmain.xml

fragmain.xml 未來放置 Fragment 的 ViewGroup 按鈕

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <LinearLayout android:id="@+id/fragment_container" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <Button android:id="@+id/back_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text=" 前一頁 " android:textsize="30sp" /> <Button android:id="@+id/next_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text=" 下一頁 " android:textsize="30sp" /> </LinearLayout> 按鈕 Button </LinearLayout>

建立 class DetailsFragment 繼承自 class Fragment

newinstance 方法回傳一個 fragment 建立 fragment 物件 在 fragment 物件上綁定參數

附加到 root layout Fragment 自己的 layout

public static DetailsFragment newinstance(context context, int index) { ctx = context; DetailsFragment f = new DetailsFragment(); Bundle args = new Bundle(); // 透過 Bundle 設定 index 參數 args.putint("index", index); f.setarguments(args); return f; } public int getshownindex() { // 取得 index 值 return getarguments().getint("index", 0); } @Override public View oncreateview(layoutinflater inflater, @Nullable ViewGroup container, Bundle savedinstancestate) { // Fragment 的 layout v=inflater.inflate(r.layout.fragment_sub,container,false); TextView text=(textview)v.findviewbyid(r.id.text_view); text.settext("page=" + getshownindex()); return v; }

fragment_sub.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/text_view" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="fragment" /> </LinearLayout>

繼承 FragmentActivity 建立主程式 GoFragment.java

private Button firstbtn, secondbtn; private int page = 1;

protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.fragmain); // 找到按鈕 firstbtn = (Button) findviewbyid(r.id.back_button); secondbtn = (Button) findviewbyid(r.id.next_button); // 先顯示第一頁 changefragment(detailsfragment.newinstance(this,page)); // 按鈕對應事件 firstbtn.setonclicklistener(new View.OnClickListener() { @Override public void onclick(view v) { if (page > 1) { // 退後一頁 changefragment(detailsfragment.newinstance(fragmain.this, --page)); } else { // 維持在第一頁 changefragment(detailsfragment.newinstance(fragmain.this, page)); } } }); secondbtn.setonclicklistener(new View.OnClickListener() { @Override public void onclick(view v) { changefragment(detailsfragment.newinstance(fragmain.this, ++page)); } }); }

在 frgmain.xml 中

// 設定 fragment 版面 private void changefragment(fragment f) { FragmentTransaction transaction = getsupportfragmentmanager().begintransaction(); // 要取代的位置 transaction.replace(r.id.fragment_container, f); // 觸發 DetailsFragment 內的 oncreateview transaction.commitallowingstateloss(); }

可以設計兩個不同版面來切換 延伸應用

fragment_sub1.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" > <ImageView android:id="@+id/imageview1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@mipmap/ic_launcher" /> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="button" /> </LinearLayout>

@Override public View oncreateview(layoutinflater inflater, @Nullable ViewGroup container, Bundle savedinstancestate) { // 對應的畫面 switch (getshownindex()) { case 1: v = inflater.inflate(r.layout.fragment_sub, container, false); TextView text = (TextView) v.findviewbyid(r.id.text_view); text.settext("page" + getshownindex()); break; case 2: v = inflater.inflate(r.layout.fragment_sub1, container, false); Button bt1 = (Button) v.findviewbyid(r.id.button1); bt1.setonclicklistener(new View.OnClickListener() { @Override public void onclick(view v) { Toast.makeText(ctx, "Fragment page2", Toast.LENGTH_LONG).show(); } }); break; default: v = inflater.inflate(r.layout.fragment_sub, container, false); TextView text1 = (TextView) v.findviewbyid(r.id.text_view); text1.settext("page" + getshownindex()); break; } return v; }

後記 類似功能用 ViewFlipper 也可以達成 用 Viewflipper 包多個要切換的頁面, 在同一支程式內做切換 但一個版面可以建立多個 Fragment 做多個局部切換 一個 Fragment 可以在多個 Activity 中被重複使用

依據旋轉或大小動態改變載入 Fragment

首先建立可以並排的 Fragment 直接在 xml 中載入使用

建立 fragment_1.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:background="#ff00ff" > <TextView android:id="@+id/text_view" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text=" 我是 fragment1" android:textsize="30sp"/> </LinearLayout>

建立 fragment_2.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:background="#ffff00" > <ImageView android:id="@+id/imageview1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@mipmap/ic_launcher" /> </LinearLayout>

只建立 oncreateview 就可以 建立 Fragment_1.java

只建立 oncreateview 就可以 建立 class Fragment_2

@TargetApi(Build.VERSION_CODES.HONEYCOMB) public class Fragment_1 extends Fragment { @Override public View oncreateview(layoutinflater inflater, ViewGroup container, Bundle savedinstancestate) { return inflater.inflate(r.layout.fragment_1, container, false); } } @TargetApi(Build.VERSION_CODES.HONEYCOMB) public class Fragment_2 extends Fragment { @Override public View oncreateview(layoutinflater inflater, ViewGroup container, Bundle savedinstancestate) { return inflater.inflate(r.layout.fragment_2, container, false); } }

建立主畫面 parrelfragment.xml <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:id="@+id/fragment1" android:name="tw.edu.ctu.imetest.myapplication.fragment_1" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" /> <fragment android:id="@+id/fragment2" android:name="tw.edu.ctu.imetest.myapplication.fragment_2" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" /> </LinearLayout> 各自載入對應的 class

result 可以看到兩個並排, 但是沒有動態偵測手機或平板加以改變

依據旋轉或大小動態改變載入 Fragment 建立兩個 Activity(TitleActivity 與 DetailActivity), 各自對應一個 Fragment 建立兩個 Fragment 可以沿用前面的 Fragment_1( 搭配 fragment_1.xml) 與 Fragment_2 ( 搭配 viewer.xml, 因為後續要做互動 ) 建立兩個主畫面 (fragmenta.xml) 給 TitleActivity 使用, 一個用於直向 (res/layout), 一個用於橫向 (res/layout-land), fragmentb.xml 給 DetailActivity 使用

進入點 TitleActivity 相對關係 +fragmenta.xml 橫向 : Fragment_1 fragment_1.xml 直接互動 +Fragment_2 viewer.xml Intent 直向 : Fragment_1 fragment_1.xml DetailActivity +fragmentb.xml + FragmentB viewer.xml

TitleActivity.java 要有兩個, 分別用於直向與橫向

res/layout/fragmenta.xml Fragment_1 直向時, 只使用一個 Fragment

<?xml version="1.0" encoding="utf-8"?> <fragment xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/titles" android:name="tw.edu.ctu.rcjao.fragment.androidfragmentsample.fragment_1" android:layout_width="match_parent" android:layout_height="match_parent" />

res/layout-land/fragmenta.xml 橫向時, 使用兩個 Fragment <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal"> <fragment android:name="ctu.im.rcjao.hw1963001.fragment_1" android:layout_width="0dp" android:layout_height="match_parent" android:id="@+id/titles" android:layout_weight="45"> </fragment> <fragment android:name="ctu.im.rcjao.hw1963001.fragment_2" android:layout_width="0dp" android:layout_height="match_parent" android:id="@+id/viewers" android:layout_weight="55"> </fragment> </LinearLayout>

目前到這旋轉螢幕, 畫面是可以變化, 但是沒有動作

DetailActivity.java 一個就可以

fragmentb.xml Fragment_2

<?xml version="1.0" encoding="utf-8"?> <fragment xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/titles" android:name="tw.edu.im.tv.myapplication.fragment_2" android:layout_width="match_parent" android:layout_height="match_parent" />

Fragment_1.java (I) Fragment_1 本身是 List, 不需要再建立 layout( 不需要 oncreateview 方法 )

Fragment_1.java (II) Fragment_2 Fragment_2 看目前 Fragment_2 是否存在, 如果不在表示直向, 用 Intent 跳過去如果存在, 直接更新 Fragment_2 上面的顏色

@TargetApi(Build.VERSION_CODES.HONEYCOMB) public class Fragment_1 extends ListFragment { private final String[] tutoriallist = {"RED", "GREEN", "BLUE",}; @Override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setlistadapter(new ArrayAdapter(getActivity(). getapplicationcontext(), android.r.layout.simple_list_item_activated_1, tutoriallist) { @Override public View getview(int position, View convertview, ViewGroup parent) { View view = super.getview(position, convertview, parent); TextView text = (TextView) view.findviewbyid(android.r.id.text1); text.settextcolor(color.black); return view; } } ); } } @Override public void onlistitemclick(listview l, View v, int position, long id) { // TODO Auto-generated method stub super.onlistitemclick(l, v, position, id); Fragment_2 viewer = (Fragment_2) getfragmentmanager().findfragmentbyid(r.id.viewers); if (viewer == null!viewer.isinlayout()) { Intent launchingintent = new Intent(getActivity(), DetailActivity.class); launchingintent.putextra("color_type", tutoriallist[position]); startactivity(launchingintent); } else { viewer.updatecolor(tutoriallist[position]); } }

Fragment_2.java Fragment_2 從 Fragment_1 傳來的 Fragment_2 自己的 LAYOUT

@TargetApi(Build.VERSION_CODES.HONEYCOMB) public class Fragment_2 extends Fragment { TextView mtext; @Override public View oncreateview(layoutinflater inflater, ViewGroup container,bundle savedinstancestate) { Intent launchingintent = getactivity().getintent(); String color = launchingintent.getstringextra("color_type"); View viewer = (View) inflater.inflate(r.layout.viewer, container, false); mtext = (TextView) viewer.findviewbyid(r.id.textsample); updatecolor(color); return viewer; } } public void updatecolor(string color) { if(color!= null) if(color.equals("red")) mtext.setbackgroundcolor(color.red); else if(color.equals("blue")) mtext.setbackgroundcolor(color.blue); else if(color.equals("green")) mtext.setbackgroundcolor(color.green); }

viewer.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:gravity="center" android:orientation="horizontal" > <TextView android:id="@+id/textsample" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#cc9988" android:gravity="center" android:text="this is the sample text" android:textcolor="#000000" /> </LinearLayout>

result