【Android】使用Intent實現數據傳遞之返回結果


例子來自老羅的Android視頻。


前面幾篇blog僅僅是向Activity傳遞數據,但有時候我們需要從Activity中返回數據,雖然返回數據也可以採用前面幾種方法,但一般建議使用Intent對象,而且需要使用stratActivityForResult方法。


1.在Main的button回調函數中,我們這樣寫:

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

除此之外我們還需要重寫startActivityForResult方法:

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

2。在Other中我們這樣寫:

@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.other);
		
		button = (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 + "=" + "?");
		
		button.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的聲明週期
			}
		});
	}

注意對比不同:

在main中使用了startActivityForResult方法,在Other中設置了setResult,而且後面執行finish。

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