Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Activity實例詳解之啟動activity並返回結果

Activity實例詳解之啟動activity並返回結果

編輯:關於Android編程

先給大家展示下效果展示圖:

1 簡介

如果想在Activity中得到新打開Activity 關閉後返回的數據,需要使用系統提供的startActivityForResult(Intent intent, int requestCode)方法打開新的Activity,新的Activity 關閉後會向前面的Activity傳回數據,為了得到傳回的數據,必須在前面的Activity中重寫onActivityResult(int requestCode, int resultCode, Intent data)方法。

public class MainActivity extends Activity {
private final static String TAG="MainActivity";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btnOpen=(Button)this.findViewById(R.id.btnOpen);
btnOpen.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
//得到新打開Activity關閉後返回的數據
//第二個參數為請求碼,可以根據業務需求自己編號
startActivityForResult(new Intent(MainActivity.this, OtherActivity.class), 1);
}
});
}
/**
* 為了得到傳回的數據,必須在前面的Activity中(指MainActivity類)重寫onActivityResult方法
*
* requestCode 請求碼,即調用startActivityForResult()傳遞過去的值
* resultCode 結果碼,結果碼用於標識返回數據來自哪個新Activity
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
String result = data.getExtras().getString("result");//得到新Activity 關閉後返回的數據
Log.i(TAG, result);
}
}

當新Activity關閉後,新Activity返回的數據通過Intent進行傳遞,android平台會調用前面Activity 的onActivityResult()方法,把存放了返回數據的Intent作為第三個輸入參數傳入,在onActivityResult()方法中使用第三個輸入參數可以取出新Activity返回的數據。

2 setResult

使用startActivityForResult(Intent intent, int requestCode)方法打開新的Activity,新Activity關閉前需要向前面的Activity返回數據需要使用系統提供的setResult(int resultCode, Intent data)方法實現:

public class OtherActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.other);
Button btnClose=(Button)findViewById(R.id.btnClose);
btnClose.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
//數據是使用Intent返回
Intent intent = new Intent();
//把返回數據存入Intent
intent.putExtra("result", "My name is linjiqin");
//設置返回數據
OtherActivity.this.setResult(RESULT_OK, intent);
//關閉Activity
OtherActivity.this.finish();
}
});
}
}

setResult()方法的第一個參數值可以根據業務需要自己定義,上面代碼中使用到的RESULT_OK是系統Activity類定義的一個常量,值為-1,代碼片斷如下:

public class android.app.Activity extends ......{
public static final int RESULT_CANCELED = 0;
public static final int RESULT_OK = -1;
public static final int RESULT_FIRST_USER = 1;
}

說明:當點擊“打開新的Activity”按鈕,會跳轉到“我是新打開的Activity”頁面;

當點擊“關閉”按鈕,關閉當前頁面,同時跳轉到“我是舊的Activity”頁面,且會傳遞result參數給前一個Activity

3請求碼的作用

使用startActivityForResult(Intent intent, int requestCode)方法打開新的Activity,我們需要為startActivityForResult()方法傳入一個請求碼(第二個參數)。請求碼的值是根據業務需要由自已設定,用於標識請求來源。例如:一個Activity有兩個按鈕,點擊這兩個按鈕都會打開同一個Activity,不管是那個按鈕打開新Activity,當這個新Activity關閉後,系統都會調用前面Activity的onActivityResult(int requestCode, int resultCode, Intent data)方法。在onActivityResult()方法如果需要知道新Activity是由那個按鈕打開的,並且要做出相應的業務處理,這時可以這樣做:

@Override public void onCreate(Bundle savedInstanceState) {
....
button1.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
startActivityForResult (new Intent(MainActivity.this, NewActivity.class), 1);
}
});
button2.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
startActivityForResult (new Intent(MainActivity.this, NewActivity.class), 2);
}
});
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch(requestCode){
case 1:
//來自按鈕1的請求,作相應業務處理
case 2:
//來自按鈕2的請求,作相應業務處理
}
}
}

4 結果碼的作用

在一個Activity中,可能會使用startActivityForResult()方法打開多個不同的Activity處理不同的業務,當這些新Activity關閉後,系統都會調用前面Activity的onActivityResult(int requestCode, int resultCode, Intent data)方法。為了知道返回的數據來自於哪個新Activity,在onActivityResult()方法中可以這樣做(ResultActivity和NewActivity為要打開的新Activity):

public class ResultActivity extends Activity {
.....
ResultActivity.this.setResult(1, intent);
ResultActivity.this.finish();
}
public class NewActivity extends Activity {
......
NewActivity.this.setResult(2, intent);
NewActivity.this.finish();
}
public class MainActivity extends Activity { // 在該Activity會打開ResultActivity和NewActivity
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch(resultCode){
case 1:
// ResultActivity的返回數據
case 2:
// NewActivity的返回數據
}
}
}

5 Demo源碼:

TestResultActivity.java

package mm.shandong.com.testresult;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
public class TestResultActivity extends AppCompatActivity {
EditText editTextBrand;
RadioGroup radioGroup;
TextView textViewXH;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_result);
editTextBrand = (EditText) findViewById(R.id.editTextBrand);
radioGroup = (RadioGroup) findViewById(R.id.radioGroup);
textViewXH = (TextView) findViewById(R.id.textViewXH);
RadioButton radionButton = (RadioButton) radioGroup.getChildAt(0);
radionButton.setChecked(true);
}
///跳轉到選擇品牌界面
public void selectBrand(View view) {
Intent intent = new Intent(this, TestResultActivity1.class);
startActivityForResult(intent, 1);
}
///選擇要購買的電腦
public void selectCompute(View view) {
Intent intent = new Intent(this, TestResultActivity2.class);
String brand = editTextBrand.getText().toString();
RadioButton radionButton =
(RadioButton) radioGroup.findViewById(radioGroup.getCheckedRadioButtonId());
String nc = radionButton.getText().toString();
intent.putExtra("brand", brand);
intent.putExtra("nc", nc);
startActivityForResult(intent, 2);
textViewXH.setText("");
}
///activity請求返回的回調
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
switch (requestCode) { //resultCode為回傳的標記
case 1:
if (resultCode == 2) {
String brand = intent.getStringExtra("brand");
editTextBrand.setText(brand);
}
break;
case 2:
if (resultCode == 3) {
String xh = intent.getStringExtra("xh");
textViewXH.setText(xh);
}
break;
}
}
}

TestResultActivity1

package mm.shandong.com.testresult;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class TestResultActivity1 extends AppCompatActivity {
ListView listView;
String[] brands = new String[]{"聯想", "戴爾"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_result1);
listView = (ListView) findViewById(R.id.listView);
ArrayAdapter arrayAdapter = new ArrayAdapter(this,
android.R.layout.simple_list_item_checked, brands);
listView.setAdapter(arrayAdapter);
listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
}
///提交選擇的品牌結果
public void submit(View view) {
int index = listView.getCheckedItemPosition();
if (index < 0) {
Toast.makeText(this, "請選擇品牌", Toast.LENGTH_SHORT).show();
return;
}
String brand = (String) listView.getItemAtPosition(index);
int resultCode = 2;
Intent intent = getIntent();
intent.putExtra("brand", brand);
setResult(2, intent);
finish();
}
}

TestResultActivity2

package mm.shandong.com.testresult;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class TestResultActivity2 extends AppCompatActivity {
ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_result2);
Intent intent=getIntent();
String brand=intent.getStringExtra("brand");
String nc=intent.getStringExtra("nc");
Map map=initData();
List<String> lists= (List<String>) map.get(brand+nc);
listView= (ListView) findViewById(R.id.listView);
ArrayAdapter arrayAdapter=new ArrayAdapter(this,
android.R.layout.simple_list_item_checked,lists);
listView.setAdapter(arrayAdapter);
listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
}
///提交選擇的電腦型號
public void submit(View view){
int index= listView.getCheckedItemPosition();
if(index<0){
Toast.makeText(this,"請選擇型號",Toast.LENGTH_SHORT).show();
return ;
}
String xh= (String) listView.getItemAtPosition(index);
int resultCode=2;
Intent intent=getIntent();
intent.putExtra("xh",xh);
setResult(3,intent);
finish();
}
///初始化數據源
public Map initData(){
Map map=new HashMap();
List<String> lists=new ArrayList<>();
lists.add("聯想1G0001");
lists.add("聯想1G0002");
map.put("聯想1G",lists);
lists=new ArrayList<>();
lists.add("聯想2G0001");
lists.add("聯想2G0002");
map.put("聯想2G",lists);
lists=new ArrayList<>();
lists.add("戴爾1G0001");
lists.add("戴爾1G0002");
map.put("戴爾1G",lists);
lists=new ArrayList<>();
lists.add("戴爾2G0001");
lists.add("戴爾2G0002");
map.put("戴爾2G",lists);
return map;
}
}

以上所述是小編給大家介紹的Activity實例詳解之啟動activity並返回結果,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對本站網站的支持!

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