0
我有兩個活動主要活動和活動二, 基本上我試圖從活動二傳遞文本到主要活動,當我點擊主要活動 中的按鈕,但它始終檢索空
任何幫助,爲什麼它不發回消息從兒童活動傳遞數據到主要活動
是主要活動代碼:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button two = (Button) findViewById(R.id.button);
Recieve =(TextView) findViewById(R.id.textView2);
two.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
sendMessage();
}
});
}
public void sendMessage() {
Intent intent = new Intent(this, Activity2.class);
startActivityForResult(intent, REQUEST_CODE);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
String requiredValue = data.getStringExtra("Key");
Recieve.setText(requiredValue);
}
}
那就是活性2代碼:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_2);
send();
}
public void send(){
String message ="hello";
Intent intent = new Intent();
intent.putExtra("key", message);
setResult(RESULT_OK, intent);
finish();
}
}
用作鍵的靜態最終字符串必須是公共的才能用於多個類(活動)。我還要補充說,最好將它設置在接收數據的活動中(MainActivity在這裏),所以其他活動可以一致地使用它,而不必加載第三方活動來提供響應。 – Feuby
@Feuby:「必須公開才能用於多個類」 - 只有當它們是不同的Java包時。否則,私人包就足夠了。 – CommonsWare
是的,它確實爲我工作,謝謝@CommonsWare –