android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="myButton1" />
android:id="@+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="myButton2" />
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
Button button1=(Button)findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// //——下面返回數據給上一個活動
//跳轉到活動MyActivity2
//第一個參數:上下文,第二個參數:目標活動類
Intent intent = new Intent(MainActivity.this,SecondActivity.class); //顯式Intent
//向活動MyActivity2傳遞數據
intent.putExtra("info", "我來自活動1");
//啓動活動
startActivityForResult(intent, 0);
}
});
}
/**
* 接受活動返回的數據,該方法對應於startActivityForResult(intent, 0)方法,請求碼只要是唯一值就好,這裏傳入了0
* requestCode:請求碼
* resultCode:返回數據時的處理結果
* data:返回數據的Intent
*/
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//進行判斷
if(0 == requestCode && resultCode == RESULT_OK){
//獲取數據
String feedBack = data.getStringExtra("feedBack");
Toast.makeText(getApplicationContext(), feedBack, Toast.LENGTH_SHORT).show();
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//隱藏標題欄
requestWindowFeature(Window.FEATURE_NO_TITLE);
//加載自定義佈局文件 activity2_my.xml
setContentView(R.layout.second_layout);
//接受活動1傳遞來的數據
Intent intent = getIntent();
String info = intent.getStringExtra("info");
//即獲取主活動傳遞來的數據,使用Toast顯示
Toast.makeText(getApplicationContext(), info, Toast.LENGTH_SHORT).show();
//——爲Button2添加點擊監聽事件:創建一個Intent,回傳數據給主活動,同時銷燬當前活動。使用setResult方法回傳數據。
Button button2 = (Button) findViewById(R.id.button2);
//爲Button2添加點擊監聽事件
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//構建一個Intent 返還數據,創建一個Intent,回傳數據給主活動,同時銷燬當前活動。使用setResult方法回傳數據。
Intent intent2 = new Intent();
intent2.putExtra("feedBack", "我來自活動2,我已經收到了你的信息,這是我給你的反饋!");
setResult(RESULT_OK, intent2); //返還數據
finish();//銷燬當前活動
}
});
}
//需要注意的是,用戶按下back時也可以返回,因此在活動MyActivity2中還需要重寫onBackPressed方法
public void onBackPressed() {
//構建一個Intent 返還數據
Intent intent2 = new Intent();
intent2.putExtra("feedBack", "我來自活動2,我已經收到了你的信息,這是我給你的反饋!");
setResult(RESULT_OK, intent2); //返還數據
finish();//銷燬當前活動
}
}
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="com.administrator.intentputextra.SecondActivity"></activity>