【发布时间】:2013-04-14 17:55:06
【问题描述】:
假设我们通过单击按钮将从文本框接收到的数据从活动 Main_Activity 发送到另一个活动 Display_Message_Activity。
在 Main_Activity 中: Step-1: 声明最终的字符串
public final static String EXTRA_MESSAGE="com.example.myfirstapp.MESSAGE";
第 2 步:将点击分配给按钮
public void sendMessage(View view) {
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
第三步:在DisplayMessageActivity中,
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the message from the intent
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
// Create the text view
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(message);
// Set the text view as the activity layout
setContentView(textView);
}
现在我的问题是我们为什么要使用 intent.getStringExtra(MainActivity.EXTRA_MESSAGE); ? 取而代之的是,我们可以在按钮单击时轻松更新静态字符串 MainActivity.EXTRA_MESSAGE 的值,然后直接访问它并将 EXTRA_MESSAGE 字符串的值分配给 *message 字符串在显示消息活动中。 我是说, 步骤:1
public static String EXTRA_MESSAGE="com.example.myfirstapp.MESSAGE";
步骤:2
public void sendMessage(View view) {
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
EXTRA_MESSAGE=message;
startActivity(intent);
}
步骤:3
.
.
.
String message=MainActivity.EXTRA_MESSAGE;
.
.
.
那么为什么在消息传递的情况下首选使用 Intent 呢?
【问题讨论】:
标签: android android-intent static