1. 程式人生 > >Android子碎片如何銷燬自己並回到父碎片活動的方法

Android子碎片如何銷燬自己並回到父碎片活動的方法

如圖所示,Activity內嵌了Fragment,Fragment裡面有內嵌了一個子Fragment。現在我們要在點選子碎片中的按鈕後使子碎片銷燬,並回到父碎片的活動中去。

廢話不多說,先看效果圖和最終要用到的程式碼:

在子碎片(ChildFrag.java)中:

Fragment fragment = ChildFrag.this.getParentFragment(); // getParentFragment() 是 Android 內建的方法
ParentFrag frag = (ParentFrag) fragment; // 注意一定要進行這個型別轉化,使 fragment 泛型變為某個特定的父碎片  
frag.finishMyChild(); // 這個方法是在父碎片中定義的,程式碼見下面

在父碎片(ParentFrag.java)中呼叫“銷燬”方法:

public class ParentFrag extends Fragment {

    private Fragment child;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.frag_parent, container, false
); child = new ChildFrag(); return view; } public void finishMyChild(){ FragmentManager manager = getChildFragmentManager(); FragmentTransaction transaction = manager.beginTransaction(); transaction.remove(child); transaction.commit(); } }

相關佈局與程式碼

MainActivity & activity_main

主佈局裡面只裝了一個父碎片,很簡單:

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.likianta.androidtest.MainActivity">

    <fragment
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/frag_parent"
        android:name="com.likianta.androidtest.ParentFrag"/>

</RelativeLayout>

主活動是靜態佈局,所以更簡單(這裡我用的是v4庫的fragment):

MainActivity.java

package com.likianta.androidtest;

import android.support.v4.app.FragmentActivity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

public class MainActivity extends FragmentActivity {

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

}

ParentFrag & frag_parent

第一個文字view用於顯示一串文字;第二個是FrameLayout,我們用它來作為待會兒盛裝子碎片的容器;最後底部是一個Button,用於跳轉到子碎片活動:

frag_parent.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/parent_txt"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="I'm parent frag"
        android:textSize="32sp" />

    <FrameLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="300dp"
        android:layout_marginTop="40dp">

    </FrameLayout>

    <Button
        android:id="@+id/parent_to_child"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:text="see my child" />

</RelativeLayout>

父碎片程式碼如下,點選按鈕可裝載子碎片,另外還寫了一個finishMyChild()方法,將會被用於銷燬子碎片:

ParentFrag.java

package com.likianta.androidtest;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

/**
 * Created by Likianta_Dodoora on 2018/1/11 0011.
 */

public class ParentFrag extends Fragment {

    TextView txt;
    private Fragment child;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.frag_parent, container, false);

        Button button = (Button) view.findViewById(R.id.parent_to_child);
        txt = (TextView) view.findViewById(R.id.parent_txt);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                FragmentManager manager = getChildFragmentManager();
                FragmentTransaction transaction = manager.beginTransaction();
                child = new ChildFrag();
                transaction.replace(R.id.container, child);
                transaction.commit();
            }
        });

        return view;
    }

    public void finishMyChild(){
        FragmentManager manager = getChildFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        transaction.remove(child);
        transaction.commit();
    }
}

ChildFrag & frag_child

frag_child.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="300dp"
    android:layout_height="200dp"
    android:background="#dfdfdf">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Hi, I'm child frag"
        android:textSize="28sp"/>

    <Button
        android:id="@+id/child_finish"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:text="finish myself" />

</RelativeLayout>

ChildFrag.java

package com.likianta.androidtest;

import android.graphics.PointF;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

/**
 * Created by Likianta_Dodoora on 2018/1/11 0011.
 */

public class ChildFrag extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.frag_child, container, false);

        Button button = (Button) view.findViewById(R.id.child_finish);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Fragment fragment = ChildFrag.this.getParentFragment(); // getParentFragment() 是 Android 內建的方法,此方法可返回一個碎片
                ParentFrag frag = (ParentFrag) fragment; // 注意一定要進行這個型別轉化,使 fragment 泛型變為某個特定的父碎片

                // 獲得了父碎片例項後,不但可以引用父碎片的變數,還可以使用父碎片的方法:

                frag.txt.setText("I'm parent frag\nI'M COMING BACK.");
                //frag.txt.setTextColor(0xff123445); // 改變一下顏色,0x表示整型,ff表示不透明度100%,123445是顏色的十六進位制數,一定要這樣子寫!

                frag.finishMyChild();
            }
        });

        return view;
    }

}

參考

相關推薦

Android碎片如何銷燬自己回到碎片活動方法

如圖所示,Activity內嵌了Fragment,Fragment裡面有內嵌了一個子Fragment。現在我們要在點選子碎片中的按鈕後使子碎片銷燬,並回到父碎片的活動中去。 廢話不多說,先看效果圖和最終要用到的程式碼: 在子碎片(Chil

再談包訪問權限 類為何不能使用類protected方法

空間 什麽 -i height nested blog size void main 可見範圍 權限的含義應該理解為控制範圍,要把它理解成一個限制範圍的空間,更為準確的說叫做可見範圍 訪問控制的等級,從最大權限到最小權限依次為:public、protected

vue 頁面怎麽調用頁面的方法

back name bsp round rip vid () com app 首先環境要說一下,是vue-cli 腳手架 搭的webpack 下面是父頁面的寫法 <template> <div id="app"> <router

元素float後撐起元素的方法

1.給父元素也新增float 讓父元素與子元素一起脫離文件流浮動起來可以讓子元素在父元素內,這樣父元素就能自適應子元素的高度,但是會影響父元素之後的元素排列,甚至影響佈局。 2.給父元素一個固定高度 此方法適用於子元素高度已知並且固定的情況。 3.新建一個空的div 為這

再談包訪問許可權 類為何不能使用類protected方法

可見範圍 許可權的含義應該理解為控制範圍,要把它理解成一個限制範圍的空間,更為準確的說叫做可見範圍 訪問控制的等級,從最大許可權到最小許可權依次為:public、protected、包訪問許可權(沒有關鍵詞)、和private public 所有地方都可以訪問,沒有任何疑問 priva

java基礎學習之——類重寫(覆蓋)類的方法必須滿足的條件

子類重寫(覆蓋)父類的方法必須滿足的條件:父類中的方法在子類中必須可見,即子類繼承了父類中的該方法(可以顯式的使用super關鍵字來訪問父類中的被重寫的方法),如果父類中的方法為private型別的,那麼子類則無法繼承,也無法覆蓋。子類和父類的方法必須是例項方法,如果父類是

Android執行緒中更新UI的3種方法

//UI執行緒中執行 new DownloadImageTask().execute( "www.91dota.com" ); private class DownloadImageTask extends AsyncTask { protected String doInBackgrou

[QT]MdiArea窗口的管理,攔截窗口關閉消息窗口處理

pos 管理 log info 圖片 再次 com window remove 在子窗口註冊事件過濾器,然後在父窗口重寫事件過濾器 中間可調用event->ignore()來忽略此事件,若沒有調用此函數,子窗口會繼續處理此事件 函數removeSubWindow

使用jbox彈窗,關閉窗體重新整理窗體

$.jBox.open("iframe:Staff.aspx"  "子窗體A", 650, 400, { buttons: {}, top: '10%' }); 開始使用parent.location.reload(),  IE總是彈出“若再次顯示該網頁web瀏覽器需要重

微信小程式:wx.navigateTo從頁面跳頁面,頁面不重新整理的問題

先簡要說說小程式的生命週期: 應用的生命週期:App({…}) 用來註冊小程式,指定小程式的生命週期 頁面的生命週期:Page({…}) 註冊頁面,指定頁面的生命週期 具體註冊函式的內容見小程式官網API 其中有三個生命週期函式的觸發順序:onLoad-

[css]如何讓一個元素div1的寬度由元素的寬度決定,超出元素div0

這裡針對的都是block的元素 div0   div1     div1_1     div1_2 我希望做到的比較奇葩: 主要目的是使div橫排 若div0的寬度夠大,超過div1_1, div1_2的總和,則可以直接使用網上搜到的解決方案:使用float:left

android seekbar滑動條實現平滑滑動滾至指定值的整數倍

seekbar預設最大值為100,但當我們需要選擇的數值更大時,需制定預設最大值,但現在很多app都實現了滑動條可自由平滑的滑動,但手鬆開後,自動回滾至最接近的可選數值,下面我們就來介紹一下這種效果的實現方法 一、配置檔案xml <SeekBar

Android—點選自定義dialog窗體的控制元件銷燬自己

注意藍色字型部分 /** * 自定義彈出更新對話方塊 */ @SuppressLint("NewApi") protected void shownewsDialog(String title1, String title2, String title3) { final

androidview點選事件(click)和view長點選事件(longclick)衝突

工作中想要實現這麼一個效果: 如圖中,當child有一個click事件,parent有一個longclick事件,當長按child的時候能夠觸發parent的longclick。 遇到的問題: 當child設定click事件時,長按child不會觸發p

android 客戶端訪問自己建立的伺服器返回JSON資料進行解析學習

最近在找關於客戶端訪問伺服器開發的用例 總是去訪問別人的網站也不能對裡面的資料進行修改也不知道是怎麼實現的,自己在網上申請了一個免費的伺服器網站上傳了一個php檔案,現在就可以通過urlStr===http://1.hellowes.sinaapp.com/訪問伺服器上的資

Vue在元件中呼叫元件的方法傳參

1.在父元件 methods 中定義 show 方法,供子元件呼叫。 methods:{ show(data){ this.datamsgFormSon = data console.log(this.datamsgFormSon)

Android Studio 導入OpenCV 調試運行face-detection例子

pac oot tools property boolean adl cond dto rgb p { margin-bottom: 0.1in; direction: ltr; color: rgb(0, 0, 10); line-height: 120%; text-a

php 微信開發訂閱事件復2條消息

php 微信 peer bin name 需求 這一 access 通過 發現 在通過微信公眾平臺驗證之後,需要關註訂閱公眾號。如何獲取訂閱事件,並且在訂閱之後回復消息,如果有需求要給用戶一個數據庫表中的信息,那我們可以保存用戶openid(唯一),在這裏說一下 這個ope

關於protected在類創建類對象無法訪問類protected方法或成員

.cn logs alt ack 對象 extends 允許 javase ref 子類(父類的外部包)中訪問父類的protetcted屬性或者方法,是不可以通過創建父類對象調用的。註意:此處不討論同包下的父類子類,因為同包下所有類都可訪問protected屬性或者方

dwz中保存數據後調如何添加自己調方法

dwz form回調dwz新增後會自動幫我們進行回調,並且刷新頁面,提示成功信息。但是我們還需要在回調中添加自己的方法。怎麽做呢?我們可以自定義一個回調函數,然後先完成自己的業務,再調用dwz的回調方法,調用dwz的ajaxDone方法我們可以去源碼中拷貝。<div class="pageContent