1、主Activity里有两个Button,点击每个Button都调用第二个NewActivity。
2、从NewActivity里返回后,判断是从两个Button中的哪一个启动的NewActivity,并显示在TextView或者Toast上。
MainActivity
package com.example.intenttest; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.widget.Button; import android.widget.Toast; public class MainActivity extends Activity { private Button btn1, btn2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_main); btn1 = (Button) findViewById(R.id.bnt1); btn2 = (Button) findViewById(R.id.bnt2); btn1.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub startActivityForResult(new Intent(MainActivity.this, NewActivity.class), 1); } }); btn2.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub startActivityForResult(new Intent(MainActivity.this, NewActivity.class), 2); } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { // TODO Auto-generated method stub switch (requestCode) { case 1 : Toast.makeText(MainActivity.this, "第一个Button", Toast.LENGTH_SHORT).show(); break; case 2 : Toast.makeText(MainActivity.this, "第二个Button", Toast.LENGTH_SHORT).show(); break; default : break; } } }
NewActivity
package com.example.intenttest; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.Window; public class NewActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.new_activity); setResult(RESULT_OK, new Intent().putExtra("result", "返回的数据")); } }
时间: 2024-11-12 20:53:25