返回列表 發帖

Android App - intent activity 數據交換

建立兩個 Activities.
                        
第一個Activity
package sample.android.intent.explicit;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

public class ActivityOne extends Activity {
private static final int REQUEST_CODE = 10;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}


public void onClick(View view) {
Intent i = new Intent(this, ActivityTwo.class);

i.putExtra("Value1", "你好嗎"); //Value1 是一個變數的名字,要與 ActivityTwo 中對應

i.putExtra("Value2", "早晨! ");

// REQUEST_CODE 是用來判斷回來的 onActivityResult 是否你需要的


startActivityForResult(i, REQUEST_CODE);

}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK && requestCode == REQUEST_CODE) {
if (data.hasExtra("returnKey1")) {
Toast.makeText(this, data.getExtras().getString("returnKey1"),Toast.LENGTH_SHORT).show();
}
}
}
}
               
第二個Activity                         
package sample .android.intent.explicit;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

public class ActivityTwo extends Activity {     
/** Called when the activity is first created. */

@Override

public void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.second);
Bundle extras = getIntent().getExtras();
if (extras == null) {
return;
}

String value1 = extras.getString("Value1");

String value2 = extras.getString("Value2");
if (value1 != null && value2 != null) {
EditText text1 = (EditText) findViewById(R.id.input1);
EditText text2 = (EditText) findViewById(R.id.input2);
text1.setText(value1);
text2.setText(value2);
}
}

// 可以用button 來觸發 finish()

public void onClick(View view) {

finish();
}

@Override
public void finish() {
Intent data = new Intent();

data.putExtra("returnKey1", "我都很好 ");
data.putExtra("returnKey2", "晚安 ");
setResult(RESULT_OK, data);
super.finish();
}
}

參考網址
http://www.vogella.com/articles/AndroidIntent/article.html
Bill Tang     MSN:billtang@openplatform.com.hk
Openplatform Technology Co.,Ltd. 資訊坊科技有限公司  
無線工程施工、方案設計、無線產品、天饋材料、終端設備綜合供應商
Tel: 852-27491011  Fax: 852-81483532

返回列表