android中的回調請求的個人理解,android回調

來源:互聯網
上載者:User

android中的回調請求的個人理解,android回調

Fragment類提供了管理“選項菜單”的回呼函數onCreateOptionMenu(Menu,MenuInflater),調用它可以--建立“選項菜單”。

在需要“選項菜單”時,Android-OS通過Activity的FragmentManager調用Fragment的onCreateOptionMenu(Menu,MenuInflater),建立出來。

當使用者點擊“選項菜單”時,Fragment會收到onOptionItemSelected(MenuItem)方法的回調請求。

//選項菜單可以包含多個功能表項目,通過檢查功能表項目的ID,確定是哪一個,然後作出相應的動作。

 

那麼什麼是回調請求呢?????

從使用者的角度看,當我點擊“選項菜單”,會發生一件事(這個app是跳轉到另一個activity)。

代碼是在fragment中覆蓋onOptionItemSelected(MenuItem){//跳轉到另一個activity}。

 

先來看一個經典的回呼函數的例子

類比911事件-結果WTC(世貿大廈)被轟炸

1.這裡是介面、調用者、執行者

//相當於介面InApublic interface BoomWTC{  //獲得拉登的決定  public benLaDengDecide();  // 執行轟炸世貿  public void boom();}//相當於class Apublic class At$911 implements BoomWTC{//相當於【背景1】  private boolean decide;  private TerroristAttack ta;//相當於【背景2】  public At$911(){    Date now=new Date();    SimpleDateFormat myFmt1=new SimpleDateFormat("yy/MM/dd HH:mm");    this.dicede= myFmt.format(dt).equals("01/09/11 09:44");    this.ta=new TerroristAttack();  }  //獲得拉登的決定  public boolean benLaDengDecide(){    return decide;  }  // 執行轟炸世貿  public void boom(){    ta.attack(new At$911);//class A調用class B的方法傳入自己的對象,相當於【you call me】  }}//相當於class Bpublic class TerroristAttack{  public TerroristAttack(){  }  public attack(BoomWTC bmw){——這相當於【背景3】    if(bmw.benLaDengDecide()){/*class B在方法中回調class A的方法,相當於【i call you back】*/
    } }}

2.這裡是主函數

public class $911{  public static void main(String[] args){

At$911 $911=new At$911();
$911.boom();
} }

流程:在main()中建立911執行個體,調用boom()方法,該方法會調用911執行個體中的TerroristAttack執行個體的attack()方法,該方法建立911匿名執行個體,傳入attack()。

TerroristAttack的attack(BoomWTC bmw)接受一個實現BoomWTC介面的執行個體,並用介面變數bmw來引用傳入的911匿名執行個體。然後,bmw.benLaDengDecide()調用911的benLaDengDecide()方法,返回一個true(假設今天是9月11日),然後通過if判斷,執行轟炸。。。

對比來看:

androidOS main
new activity.onMenuItemSelected new 911.boom
fragment.onOptionItemSelected TerroristAttack.attack

 

因此當使用者點擊“選項菜單”時,Fragment會收到onOptionItemSelected(MenuItem)方法的回調請求,就是androidOS最終會調用onOptionItemSelected()響應--點擊選項菜單--這個事件

聯繫我們

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