Explain the syntax EditText editText = (EditText) findViewById (R.id.edit_message);

/** Called when the user clicks the Send button */
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);
}

in line

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

EditTextis a class and EditTextis an instance that we create. findViewById(R.id.edit_message)is the method, and R.id.edit_messageis the argument that we pass

But I can’t understand why there is such a (EditText)gift? Is this a constructor call?

+4
source share
5 answers

This is an explicit cast. findViewById()returns a View, and (EditText)explicitly outputs it to EditText(which is a subclass View). This works because the returned object is actually -a EditText, that is, an object of this class or one of its subclasses. If not, you will receive ClassCastException.

: http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html

+6
is it the call to constructor? 

.

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

(EditText) .

findViewById(), View object.so, EditText Object.

EditText View.

+3

...

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

findViewById(R.id.edit_message) ... , . , . Cast, . EditText (EditText).

+2

findViewById(R.id.edit_message)returns the class View. EditTextextends from this class, so we need to drop Viewin EditText. If we need a view class, we can simply writeView v = findViewById(R.id.some_view);

+1
source

<EditText android:id="@+id/edit_message" <<<<<<<<<<<<<<<<<< android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:hint="@string/edit_message"/>

-1
source

Source: https://habr.com/ru/post/1527697/


All Articles