【Android】18、從意圖返回結果

stratActivity()方法調用另一個活動,但並沒有返回結果給當前活動。例如,您可能有一個提示用戶輸入用戶名和密碼的活動。

用戶在這個活動中輸入的信息需要回傳給調用它的活動來做進一步處理。如果需要從一個活動中回傳數據,應該使用startActivityForResult()方法。

延續上一個工程項目。

1、在secondactivity.xml中添加以下代碼

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Please enter your name"/>
<EditText
    android:id="@+id/txt_username"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />
<Button
    android:id="@+id/btn_ok"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="OK"
    android:onClick="onClick"/>

2、在secondactivity.java文件中添加以下代碼

public void onClick(View view){
    Intent data =new Intent();

    //--get the EditText View--
    EditText txt_username= (EditText) findViewById(R.id.txt_username);

    //--set the data to pass back--
    data.setData(Uri.parse(txt_username.getText().toString()));
    setResult(RESULT_OK,data);

    //--closes the activity--
    finish();

3、主Activity中修改onClick()方法,並添加一個onActivityResult()方法

public void onClick(View view){
      //startActivity(new Intent("android.intent.action.SecondActivity"));
        startActivityForResult(new Intent("android.intent.action.SecondActivity"),request_Code);
    }
    public void onActivityResult(int request_Code,int result_Code,Intent data){
        if (request_Code == request_Code){
            if(result_Code == RESULT_OK){
                Toast.makeText(this,data.getData().toString(), Toast.LENGTH_LONG).show();
            }
        }

4、示例說明:

1)調用一個活動並等待從活動返回結果,需要使用startActivityForResult()方法。

該方法,除了傳入一個Intent對象,還需要傳入請求碼。請求碼僅僅是一個整數值,用來標識正在調用的活動。

這個是必須的,因爲當一個活動返回一個值時,必須有方法將它標識出來。例如,您可能同時在調用多個活動,

而一些活動可能沒有立即返回(比如正在等待服務器的響應)。當一個活動返回時,需要這個請求碼來確定實際返回的是哪一個活動。

注意:如果請求碼設爲-1,則使用startActivityForResult()方法來調用活動與使用startActivity()方法來調用時等同的。也就是說,沒有結果返回。

2)爲了使被調活動可以返回一個值給調用它的活動,可以通過setData()方法使用一個Intent對象來回傳數據。

setResult()方法設置了一個結果碼(RESULT_OK或是RESULT_CANCELLED)和回傳給調用活動的數據(一個Intent對象)

finish()方法關閉活動並將控制返回給調用者活動。

3)在調用者活動中,需要實現onActivityResult()方法,一個活動無論何時返回都需要調用這個方法。

這裏,檢驗請求和結果碼的正確性,並顯示返回的結果。返回的結果通過data參數傳入,並且通過getData()方法來獲得數據的細節。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章