简体   繁体   中英

When creating a new Activity why do we need to cast an EditText object as an EditText object?

This is part of the Android Studio Training.

EditText editText = (EditText) findViewById(R.id.edit_message);

The full method is:

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);
}

More information for this training project can be found at: http://developer.android.com/training/basics/firstapp/starting-activity.html

findViewById() returns a View by default, which doesn't include methods like getText() for example.

EditText is a subclass of View , which is why this casting works.

java.lang.Object
   ↳    android.view.View
       ↳    android.widget.TextView
           ↳    android.widget.EditText

The method findViewById returns a View , which is the generic Class for any View in Android. That means that ListView , TextView , TabHost , etc etc etc are all View s.

You have to cast it so that the object you are working with has access to the specific methods of that View . For instance, ListView has methods that EditText doesn't have.

You can cast that without worries because you know that the object you are working with is indeed an EditText . You know that because you have explictly defined an EditText when writing the layout, and have assigned an ID for this View , which you'll use later to identify this exact same View.

How do you know it is an EditText ? How does Android know it?

In fact, Android does not know it unless you tell it so, because the return type of findViewById() is View . Although EditText is one kind of View , there are others, and custom ones can be defined. The cast tells Android that you promise the View returned will be an EditText , so it can treat it as one. It requires you to cast explicitly in part for your own protection -- so that you know you are injecting your own knowledge / assumptions into the program.

If your promise is discovered to be in error, then Android will throw a ClassCastException to chastise you about that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM