安卓學習筆記(五)、使用Intent返回數據

1、

public class MainActivity extends Activity {
	private Button button;
	private final static int REQUESTCODE = 1 ;
	private EditText ps1,ps2,result;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		button = (Button) this.findViewById(R.id.button1);
		ps1 = (EditText) this.findViewById(R.id.ps1);
		ps2 = (EditText) this.findViewById(R.id.ps2);
		result = (EditText) this.findViewById(R.id.result);
		button.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				int a = Integer.parseInt(ps1.getText().toString());
				int b = Integer.parseInt(ps2.getText().toString());
				Intent intent = new Intent(MainActivity.this,OtherActivity.class);
				startActivity(intent);
				intent.putExtra("a", a);
				intent.putExtra("b", b);
				startActivityForResult(intent, REQUESTCODE);

			}
		});
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if(requestCode == 2){//大於requestCode=1的就行
			if(requestCode == 1){
				int three = data.getIntExtra("three", 0);
				result.setText(String.valueOf(three));
			}
		}
	}
}


2、

public class OtherActivity extends Activity {
	private Button button2;
	private TextView textView;
	private EditText editText;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.other);
		button2 = (Button) this.findViewById(R.id.button2);
		textView = (TextView) this.findViewById(R.id.msg);
		editText = (EditText) this.findViewById(R.id.three);
		Intent intent = getIntent();
		int a = intent.getIntExtra("a", 0);
		int b = intent.getIntExtra("b", 0);
		textView.setText(a+" + "+b+" = ?");
		button2.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent();
				int three = Integer.parseInt(editText.getText().toString());
				intent.putExtra("three", three);
				//通過Intent對象返回結果,setResult方法,以下兩句不可省略
				setResult(2,intent);	
				finish();//結束當前的activity的生命週期
				
			}
		});
	}
}


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