我想在這樣的活動上顯示一個TextView的消息:「Hello World」的機器人的TextView的setText問題
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_message);
// Get the message from the intent
Intent intent = getIntent();
// Create the text view
TextView textView = (TextView) findViewById(R.id.display_message);
if(intent.getExtras() != null){
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
textView.setTextSize(40);
textView.setText(message);
}else{
textView.setTextSize(40);
textView.setText(R.string.hello_world);
}
// Show the Up button in the action bar.
setupActionBar();
}
應該顯示的代碼當包含在intent
中的額外消息是null
,而不是hello world!
沒有顯示出來。
這是我strings.xml
:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Action Bar</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
</resources>
主要活動,其發送的消息: 「Hello World」 的
public class MainActivity extends ActionBarActivity {
public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_activity_actions, menu);
return super.onCreateOptionsMenu(menu);
//return true;
}
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);
}
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.action_search:
// openSearch();
return true;
case R.id.action_settings:
// openSettings();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
我已經添加了負責發送消息的主要活動代碼 – daiyue
intent.getExtras()!= null並不意味着intent.getStringExtra也不爲null – njzk2