Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android系統教程 >> Android開發教程 >> Android ApiDemos示例解析(11) App->Activity->Receive Result

Android ApiDemos示例解析(11) App->Activity->Receive Result

編輯:Android開發教程

startActivity可以啟動一個新的Activity,這個新的Activity與啟動它Activity之間相對獨立,不會返回給調用它的 Activity如何結果。在寫應用時,有時需要從其它Activity返回結果。Receive Result顯示了這個用法。

startActivityForResult 使用方法和startActivity類似,重要的是startActivityForResult可以從被調用的Activity返回 結果。GET_CODE為Request code,當子Activity返回結果時可以根據這個Request Code來處理Activity返回的結果。

// Definition of the one requestCode we use for receiving resuls.     
static final private int GET_CODE = 0;     

private OnClickListener mGetListener = new OnClickListener() {     
    public void onClick(View v) {     
        // Start the activity whose result we want to retrieve.  The     
        // result will come back with request code GET_CODE.     
        Intent intent = new Intent(ReceiveResult.this, SendResult.class);     
        startActivityForResult(intent, GET_CODE);     
    }     
};

當子Activity結束時,調用setResult 來設置返回結果。Receive Result例子中涉及了兩個Activity, ReceiveResult為父Activity,SendResult為子Activity返回用戶選項,返回的結果在ReceiveResult中顯示。

SendResult 返 回結果的代碼如下:

private OnClickListener mCorkyListener = new OnClickListener()     
{     
    public void onClick(View v)     
    {     
        // To send a result, simply call setResult() before your     
        // activity is finished.     
        setResult(RESULT_OK, (new Intent()).setAction("Corky!"));     
        finish();     
    }     
};     

private OnClickListener mVioletListener = new OnClickListener()     
{     
    public void onClick(View v)     
    {     
        // To send a result, simply call setResult() before your     
        // activity is finished.     
        setResult(RESULT_OK, (new Intent()).setAction("Violet!"));     
        finish();     
    }     
};

當從子Activity返回結果後,父Activity通過定義onActivityResult來處理子Activity返回的結果。

protected void onActivityResult(int requestCode, int resultCode,     
        Intent data) {     
        // You can use the requestCode to select between multiple child     
        // activities you may have started.  Here there is only one thing     
        // we launch.     
        if (requestCode == GET_CODE) {     

            // We will be adding to our text.     
           ...     
        }     
    }

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved