Android中Fragment和Activity之間的互作業碼例子

來源:互聯網
上載者:User

標籤:android   代碼   

摘要

本文介紹了Android中一個Activity中有多個Fragment的情況下,Fragment之間如何通過Activity進行互操作。

原始碼

原始碼地址為:http://download.csdn.net/detail/logicteamleader/8931199
原始碼使用ADT編寫,ADT版本為2014,Android版本為android-22。

技術要點

1.在Activity中的多個Fragment之間要互操作,一定要通過此Activity,不能直接通訊;
2.在Activity中添加Fragment可以使用id或者Tag,建議使用Tag,這樣無論該Fragment有沒有介面,都可以被Activity使用findFragmentByTag方法找到;
3.在Fragment中定義回調介面,讓Activity實現此回調介面,這樣就能讓Activity響應Fragment中的訊息;
4.不同的Fragment之間要互操作,還是通過Activity實現回調介面來實現,例如FragmentA中回調MainActivity中的OnBtnAClicked方法,而OnBtnAClicked方法中又調用了FragmentB的changeB方法,達到了兩個Fragment之間的互操作。

FragmentA的原始碼
package com.apkkids.fragmentinactivityexample;import android.app.Activity;import android.os.Bundle;import android.support.annotation.Nullable;import android.support.v4.app.Fragment;import android.view.LayoutInflater;import android.view.View;import android.view.View.OnClickListener;import android.view.ViewGroup;import android.widget.Button;import android.widget.TextView;public class FragmentA extends Fragment {    private static int iChange = 1;    private TextView tvA;    //回調介面,此介面必須被MainActivity實現,並通過此介面回調來進行Fragment和Activity之間的互操作    public OnFragmentABtnClickedListener mCallback = null;    public interface OnFragmentABtnClickedListener{        public void OnBtnAClicked();    }    @Override    public void onAttach(Activity activity) {        super.onAttach(activity);        try{            mCallback = (OnFragmentABtnClickedListener)activity;        }catch(ClassCastException e){            throw new ClassCastException(activity.toString() + " must implement OnFragmentABtnClickedListener");        }    }    @Override    @Nullable    public View onCreateView(LayoutInflater inflater,            @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {        View v = inflater.inflate(R.layout.fragmenta_layout, container, false);        tvA = (TextView) v.findViewById(R.id.tvA);        Button btnA = (Button) v.findViewById(R.id.buttonA);        //點擊此按鈕,通過回調介面,使得FragmentB中的textView改變        btnA.setOnClickListener( new OnClickListener() {            @Override            public void onClick(View v) {                if(mCallback != null){                    mCallback.OnBtnAClicked();                }            }        });        return v;    }    public void changeA() {        if (tvA != null) {            tvA.setText("TextView in FragmentA changed by FragmentB :"                    + iChange++);        }    }}
FragmentB的原始碼
package com.apkkids.fragmentinactivityexample;import android.app.Activity;import android.os.Bundle;import android.support.annotation.Nullable;import android.support.v4.app.Fragment;import android.view.LayoutInflater;import android.view.View;import android.view.View.OnClickListener;import android.view.ViewGroup;import android.widget.Button;import android.widget.TextView;public class FragmentB extends Fragment {    private static int iChange = 1;    private TextView tvB;    // 回調介面,此介面必須被MainActivity實現,並通過此介面回調來進行Fragment和Activity之間的互操作    public OnFragmentBBtnClickedListener mCallback = null;    public interface OnFragmentBBtnClickedListener {        public void OnBtnBClicked();    }    @Override    public void onAttach(Activity activity) {        super.onAttach(activity);        try {            mCallback = (OnFragmentBBtnClickedListener) activity;        } catch (ClassCastException e) {            throw new ClassCastException(activity.toString()                    + " must implement OnFragmentBBtnClickedListener");        }    }    @Override    @Nullable    public View onCreateView(LayoutInflater inflater,            @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {        View v = inflater.inflate(R.layout.fragmentb_layout, container, false);        tvB = (TextView) v.findViewById(R.id.tvB);        Button btnB = (Button) v.findViewById(R.id.buttonB);        btnB.setOnClickListener(new OnClickListener() {            @Override            public void onClick(View v) {                if (mCallback != null) {                    mCallback.OnBtnBClicked();                }            }        });        return v;    }    /**     * 改變Text的值     */    public void changeB() {        if (tvB != null) {            tvB.setText("TextView in FragmentB changed by FragmentA :"                    + iChange++);        }    }}
MainActivity的原始碼
package com.apkkids.fragmentinactivityexample;import android.os.Bundle;import android.support.v4.app.FragmentActivity;import android.support.v4.app.FragmentManager;import android.support.v4.app.FragmentTransaction;import android.view.Menu;import android.view.MenuItem;/** * @author wxb * Description:Activity中多個Fragment之間互操作的樣本,主要使用回調介面方法實現。 *             注意:Fragment之間是不能直接通訊的,一定要通過它們附著的Activity進行 * * 2015-7-24 * 下午10:02:45 */public class MainActivity extends FragmentActivity  implements FragmentA.OnFragmentABtnClickedListener,FragmentB.OnFragmentBBtnClickedListener {    private static final String FRAGMENT_A_TAG = "com.apkkids.fragmentA";    private static final String FRAGMENT_B_TAG = "com.apkkids.fragmentB";    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        FragmentA fragmentA = new FragmentA();        FragmentB fragmentB = new FragmentB();        FragmentManager fragmentManager  = getSupportFragmentManager();        FragmentTransaction  transaction = fragmentManager.beginTransaction();        //使用Tag方式添加Fragment,此外還可以用id方式添加        transaction.add(R.id.containerA, fragmentA, FRAGMENT_A_TAG);        transaction.add(R.id.containerB, fragmentB, FRAGMENT_B_TAG);        transaction.commit();    }    @Override    public boolean onCreateOptionsMenu(Menu menu) {        getMenuInflater().inflate(R.menu.main, menu);        return true;    }    @Override    public boolean onOptionsItemSelected(MenuItem item) {        int id = item.getItemId();        if (id == R.id.action_settings) {            return true;        }        return super.onOptionsItemSelected(item);    }    /* (non-Javadoc)     * @see com.apkkids.fragmentinactivityexample.FragmentA.OnAClickedListener#OnAClicked()     * FragmentA中定義的回調介面的方法,通過此方法修改FragmentB中的UI     */    @Override    public void OnBtnAClicked() {        //得到FragmentB的執行個體         FragmentManager fragmentManager  = getSupportFragmentManager();         FragmentB fragmentB = (FragmentB) fragmentManager.findFragmentByTag(FRAGMENT_B_TAG);         if(fragmentB != null)             fragmentB.changeB();    }    @Override    public void OnBtnBClicked() {        //得到FragmentA的執行個體         FragmentManager fragmentManager  = getSupportFragmentManager();         FragmentA fragmentA = (FragmentA) fragmentManager.findFragmentByTag(FRAGMENT_A_TAG);         if(fragmentA != null)             fragmentA.changeA();    }}
程式執行介面

小結

其他介面代碼請從原始碼包下載,都是不需要積分的。

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

Android中Fragment和Activity之間的互作業碼例子

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.