When coding for Android, there are two main ways I have seen to get text from an editText field. The first way seems to be very commonly used, and looks a little like this.
display = (EditText) findViewById(R.id.editText1);
displayContents = display.getText().toString();
displayTwo = (EditText) findViewById(R.id.editText2);
displayText = (Button) findViewById(R.id.button1);
displayText.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
displayTwo.setText(displayContents);
}
This seems to use a clickListener in the mainActivity class to detect the click, then finds the value of the textfields.
However, when I was looking through Google's official Android tutorial, they used an alternative method. They first added this line of code to the button:
android:onClick="sendMessage";
and then had this method instead of the onClickListener:
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);
}
After that, i created a new activity which made a new xml file with a different GUI, and a new class with the following:
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);
}
This seems to have the button broadcast a message rather than having a passive listener, and then trigger a new activity.
So after all that, I suppose my questions could be:
- Which method is better to use?
- It seems that Google's method was more to create a new app screen, but could that be done with the first method?
- I still don't completely understand Intents. Could it be explained, if you have extra time?
- The same goes for activities in Android. I think that they're used to make new screens in the app, but could somebody clarify?
No comments:
Post a Comment