activity之間的正向和反向通信

在開發過程中經常會出現一個activity的信息要傳遞給另一個activity,還有就是要上一個activity的數據傳回之前的activity

首先先使用正向傳遞:

public class IntentDemo extends Activity {  
  
    private Button button;  
  
    @Override  
    public void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.main);  
        button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {  
            @Override  
            public void onClick(View v) {  
                Intent intent = new Intent(IntentDemo.this, Other.class);  
                // 在Intent中傳遞數據  
                intent.putExtra("name", "AHuier");  
                intent.putExtra("age", 22);  
                intent.putExtra("address", "XiaMen");  
                // 啓動Intent  
                startActivity(intent);  
            }  
        });  
    }  
}  
要接收的頁面

public class Other extends Activity {  
  
    private TextView textView;  
  
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        // TODO Auto-generated method stub  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.other);  
        textView = (TextView) findViewById(R.id.msg);  
        Intent intent = getIntent();  
        int age = intent.getIntExtra("age", 0);  
        String name = intent.getStringExtra("name");  
        String address = intent.getStringExtra("address");  
  
        textView.setText("My age is " + age + "\n" + "My name is " + name + "\n" + "My address "  
                + address);  
    }  
下面是信息傳回

在要返回的頁面裏寫入

Intent backIntent = new Intent();
		backIntent.putExtra("message", displayContents);
		CaptureActivity.this.setResult(RESULT_OK, backIntent);
		CaptureActivity.this.finish();
在接的頁面裏使用startActivityForResult跳轉,onActivityResult負責接收數據

Intent intent = new Intent(MainActivity.this, CaptureActivity.class);
			
			startActivityForResult(intent, 0);

@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			String str = data.getExtras().getString("message");
			tv.setText(str);
		}
	}


在使用返回的時候記得使用finish返回到上一個,頁面記得要註冊一下


發佈了42 篇原創文章 · 獲贊 14 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章