I added the code that we were
just looking at into our app.
It says View orderSummaryTextView
= findViewById,
then we pass in the resource ID for
the order_summary_text_view.
But this causes an error in
Android Studio on the next line.
It says it cannot resolve
the method setText.
If I add another line of code here,
I can show you the types of methods
that are valid on this variable.
So, we just created
the orderSummaryTextView variable here,
and it's a TypeView, and so
on the next line,
we should be able to call methods on it.
But if you look at
the autocomplete suggestions,
these methods are actually View methods.
There's no TextView specific methods.
For example, there's no setText method.
That's why we get an error down
here when we try to call setText.
You also can't set text size, or
set text color, or any of those.
So where are all those methods?
Well, the thing is that a TextView
is a more specific type of View.
So if we want to call TextView methods
on this object we need to make sure
that this is a TextView object.
Okay.
Now the variable is a TextView object.
But then I get another error that says
incompatible types, because a TextView
is required on the right hand side,
but we're finding just a regular view.
That's because the findViewById
method returns a View.
So how do we reconcile this?
Well, since TextView is a more specific
type of View or put another way,
a TextView is a subclass of view, we can
actually use something called casting.
Casting in Java means that we can take
the View returned by this method and
actually treat it as a TextView.
So now this right hand side is
actually a TextView object, and
then we can store it inside this
orderSummaryTextView variable.
I know that this must be really
overwhelming because I just mentioned
a ton of new concepts.
Let me try to explain again.
The findViewById method turns
an object of type View.
By writing this notation,
parentheses with the desired object
data type in the middle of it.
We're casting this View into a TextView.
So the whole expression here
evaluates to a TextView object.
Then, we can store that in the variable,
on the left-hand side,
which is orderSummary TextView,
and it has a type TextView.
Now, on subsequent lines, we can call
TextView methods on this object.
Do you see now how all the text
methods are showing up here?
setAllCaps, setTextSize, and more.
So I can just erase this now,
because setText should work,
and there's no more errors.
So if we want to be able
to call TextView methods,
we need to have a TextView object.
In order to have a TextView object,
We need to call findViewById,
and then cast this View
object into a TextView.
The reason why casting works is because
this View here in the view
hierarchy is actually a TextView.
If we we try to cast it into something
like a radio button, that wouldn't work,
because the orderSummaryTextView
is actually a TextView, so
we have to cast it into
the appropriate type.
Similarly, in the displayQuantity
method, we're calling findViewById and
we're passing in this resource ID for
the quantity TextView.
This returns a View, and
we cast it into a TextView, and
we can store that inside this
variable called quantityTextView.
This variable has type TextView, and so,
on subsequent lines, we can TextView
methods on it, like setText.
Here's the updated MainActivity
code using casting.
We can cast these Views into TextViews
so that we can store them in variables
that have type TextView so
in this list of MainActivity variables,
now quantityTextView and
orderSummaryTextView are type TextView.
We can call TextView methods on these,
and we're not just limited
to treating them as Views.
And now we can call TextView
specific methods on these variables.
For example we can call setText
on the orderSummaryTextView,
and we can call setText
on the quantityTextView.
As you can see,
you have to be careful about what
data types are being used where.
So far, when we've called methods, we
haven't worried about the return value,
because the setText method
actually has no return value.
Same with
the imageView.setImageResource method.
This has no return value.
But other methods can
have return values.
For example, in the TextView class
we have a getTextSize method.
This returns an integer, so
we can store the result of this method
in a variable called size of type int.
Here's another method
that has a return value.
In the Button class you can
call the getHeight method,
and this returns an integer value, so
you can store it inside a variable.
If you tried to store this result
inside a string, for example,
you would get an error,
because this method returns an integer.
In order to know what type of data needs
to be passed into a method and what data
type gets returned back from a method,
you should check the documentation.
And for example, in the TextView class,
if you call any of these methods,
it returns a value of type int.
The return value data type is
in the left-hand column here.
For other methods, you might get
void as a return value, or booleans,
which we haven't learned about yet,
or floats or longs and etc.
This documentation page also shows
what are the expected data types for
the inputs for each method.
For example, the setTextColor method
requires an integer as input and
the return value is void,
so there's no return value.
So check the documentation to know
what data types are expected.
Otherwise, you'll get errors
in Android Studio saying that
the data types don't match.
Now it's your turn to practice.
Below are four different code examples.
Some of the code may contain errors
relating to data types not matching.
If you find an error,
describe how you're supposed to fix it
by writing it in the boxes provided.
Otherwise, you can just write No
error if the code is perfectly fine.
This is going to be challenging
quiz because we just covered
a lot of concepts, and
this code is still pretty new to you.
Take your time and check
the documentation for these methods.
Make sure that the inputs and
the return values are correct and
that, if we're declaring variables, that
we have the correct data types here.
Also, look up the documentation for
these method calls to make sure that
we're using the methods correctly.
قمت بإضافة الكود الذي كنا
نبحث عنه في تطبيقنا
يقول
View orderSummaryTextView = findViewById
ثم نمرر في المصدر
المعرف لـ order_summary_text_View
و لكن هذا يسبب خطأ
في "Android Studio" في السطر اللاحق
إنه يقول بانه غير قادر على
حل الطريقة setText
إذا أضفت سطراً برمجياً آخر هنا
يمكنني أن أريكن أنماط الطرق
الصالحة على هذا المتحول
لذا، أنشأنا المتحول
orderSummaryTextView هنا
وهو TypeView وكذلك
في السطر التالي
يجب أن كون قادرين على استدعاء الطرق فيه
ولن إذا نظرتم إلى
اقتراحات الإكمال التلقائي
هذه الطرق هي حقيقة View methods
لا يوجد طرق محددة بـ TextView
على سبيل المثال، لا يوجد طريقة setText
هذا هو السبب وراء ظهور خطأ
هنا في الأسفل عندما نحاول ان نستدعي setText
كما لا يمكنك تحديد حجم النص
أو لونه أو أي من هؤلاء
إذن أين هي كل هذه الطرق؟
حسناً، المعنى هو أن TextView
هو نمط محدد من View
إذن إذا أردنا استدعاء طرق TextView
على هذا الغرض يجب ان نتأكد
أنع غرض من TextView
حسناً
الآن المتحول هو غرض TextView
لكنني أحصل بعد ذلك على خطأ آخر
يقول أنواع غير متوافقة، لأن TextView
مطلوب على الجهة اليمنى
لكننا نجد View عادية
وهذا بسبب أن الطريقة
findViewById ترجع View
فكيف نوفق بينهما؟
حسناً، بما أن TextView هي نمط محدد أكثر
من الـ View أو بعبارة أخرى
يعتبر TextView صف فرعي من View
يمكننا حقيقة استخدام شيء يسمى القسر
يعني القسر في جافا أنه يمكننا
أخذ الـ View المرجعة من هذه الطريقة
والتعامل معها حقيقة كـ TextView
إذن أصبحت هذه الجهة اليمينية
حقيقةً غرض من TextView
و بعدها يمكننا حفظه داخل
هذا المتحول orderSummaryTextView
أعلم أن هذا يبدو فعلاً مستحوذا
لأنني ذكرت منذ قليل
طناً من المفاهيم الجديدة
اسمحوا لي أن أجرب ان أشرح مرة أخرى
تحول الطريقة
findViewById غرضاً من النمط View
من خلال كتابة هذه الملاحظة
قوسين بينهما
نمط بيانات الغرض المطلوب
نحن نقوم بقسر هذا الـ View إلى TextView
إذن كل التعبير هنا
يقيم من أجر غرض TextView
ثم يمكننا تخزين هذا ضمن المتحول
في الجهة اليسرى
وهو orderSummaryTextView
وهو من النمط TextView
الآن في الأسطر اللاحقة يمكننا
استدعاء طرق TextView على هذا الغرض
هل ترى الىن كيف أن
جميع طرق النص تظهر هنا؟
setAllCaps و setTextSize والكثير
لذا يمكنني أن امحو هذا الآن
لأن setText يبجب أن تعمل
وليس هناك المزيد من الأخطاء
لذا إن أردنا أن نكون قادرين على
استدعاء طرق TextView
يجب أن يكون لدينا غرض من TextView
للحصول على غرض من TextView
علينا أن نستدعي findViewById
و من ثم قسر هذا
الغرض من View إلى TextView
السبب وراء نجاح عملية القسر
هذا الـ View هنا في التسلسل الهرمي لـ View
هو حقيقةً TextView
إذا حاولنا قسره لشيء ما
كـ RadioButton، لن ينجح ذلك
لأن orderSummaryTextView
هو حقيقةً TextView لذا
علينا أن نقسره إلى
نوع مناسب
بالمثل، في الطريقة displayQuantity
نستدعي الطريقة findViewById
و نمرر في مصدر المعرف
من أجل quantityTextView
هذا يرجع View
ونقوم بقسره إلى TextView
ونستطيع أن نخزنه داخل هذا
المتحول المدعو quantityTextView
هذا المتحول من النوع TextView و لذا
يمكننا استدعاء طرق TextView
عليه في الأسطر اللاحقة كــ setText
واليكم كود MainActivity
المحدث باستخدام القسر
يمكننا أن نقسر هذه الـ Views إلى
TextViews حيث يمكننا تخزينها بمتحولات
من النوع TextView
حيث أنه متحولات MainActivit في هذه القائمة
الآن quantityTextView
و orderSummaryTextView هما من
النوع TextView يمكننا استدعاء
طرق TextViews عليها
و لسنا محدودين في
التعامل معهم كـ Views
و الآن يمكننا أن نستدعي الطرق
المخصصة لـ TextViews على هذه المتحولات
على سبيل لمثال يمكننا أن نستدعي setText
على orderSummaryTextView
ويمكن أن نستدعي setText
على quantityTextView
كما ترون
عليك أن تكون حذراً حول أي نمط
بيانات مستخدم وأين
حتى الآن، عندما قمنا باستدعاء الطرق
لم نعر اهتماماً للقيمة المرجعة
لأن الطريقة setText حقيقةً
لا تملك قيمة مرجعة
الشيئ نفسه من
مع الطريقة imageView.setImageResource
هذه لاتملك قيمة مرجعة
ولكن طرقأً أخرى
قد تملك قيماً مرجعة
على سبيل المثال، لدينا الطريقة getTextSize
في الصف TextView
هذه ترجع عدد صحيح لذا
يمكننا تخزين نتيجة هذه الطريقة في
متحول يدعى size من النمط int
إليكم طريقة أخرى
تملك قيمة مرجعة
يمكنك استدعاء الطريقة grtHeight
في الصف Button
وهذه تعيد قيمة صحيحة، لذا
يمكنك تخزينها في متحول
إذا حاولت تخزين هذه النتيجة
داخل سلسلة، مثلاً
ستحصل على خطأ
لأن هذه الطريقة ترجع عدداً صحيحاً
لمعرفة أي نمط بيانات يجب أن
يمرر داخل الطريقة و أي نمط
بيانات يعاد من الطريقة
عليك أن تتحقق من التوثيق
مثلاً، في الصف TextView
إذا قمت باستدعاء أي من هذه الطرق
ستعيد لك قيمة من النمط int
أنماط البيانات للقيم المعادة
في العمود هنا في الجهة اليسرى
لطرق أخرى، قد تحصل على void
كقيمة معادة أو boolean
الذي لم نتعلم عنه بعد
أو float أو long إلى آخره
صفحة التوثيق هذه تظهر أيضاً
ما هي انماط البيانات المتوقعة
لمدخلات كل طريقة
مثلاً، الطريقة setTextColor تتطلب
عدداً صحيحاً كمدخل
و القيمة المعادة void
لذا لا يوجد قيمة معادة
لذا تحقق من التوثيق لمعرفة
أي نمط بيانات هو المتوقع
وإلا ستواجه أخطاء
قي "Android Studio" تقول
أنماط البيانات غير متطابقة
الآن حان دورك للتمرن
وفيما يلي أربعة أمثلة كود مختلفة
بعض الكود قد يحوي أخطاء تعود
لعدم تطابق أنماط البيانات
إذا وجدت خطأ
صف كيف يمكن لك أن تصلحه
عن طريق الكتابة في المربعات المقدمة
عدا ذلك، يمكنك كتابة لا أخطاء
إذا كان الكود خالٍ من الأخطاء تماماً
سيشكل هذا الاختبار تحدياً
لأننا غطينا
الكثير من المفاهيم
وهذا الكود لا يزال جديداً عليك
خذ وقتك وتحقق
من توثيق هذه الطرق
تحقق من أن قيم الدخل
والخرج قيم صحيحة
انه، إذا كنا نقوم بالإعلان عن المتحولات
فإننا نستخدم نمط int هنا
ابحث أيضاً عن التوثيق من أجل
استدعاءات هذه الطرق للتأكد
من أننا نستخدم هذه الطرق بشكل صحيح
Añadí el código que vimos
en nuestra aplicación.
Dice,
View orderSummaryTextView = findViewById,
luego pasamos el identificador de recurso
para el order_summary_text_view.
Pero esto provoca un error
en Android Studio en la siguiente línea.
Dice que no puede resolver
el método setText.
Si añado otra línea de código aquí,
puedo mostrarte los tipos de métodos
que son válidos en esta variable.
Así, recién creamos la variable
orderSummaryTextView aquí
y es un TypeView,
entonces en la línea siguiente,
podemos denominarla métodos.
Pero si nos fijamos en
las sugerencias de autocompletado,
estos métodos son métodos View.
No hay métodos específicos TextView.
Por ejemplo, no hay ningún método setText.
Es por eso que tenemos un error aquí,
cuando tratamos de llamar setText.
Tampoco puedes hacer setTextSize,
o setTextColor o ninguno de los dos.
¿Dónde están todos esos métodos?
Bueno, la cosa es que un TextView
es un tipo más específico de View.
Así que si queremos llamar
a métodos TextView
a este objeto, necesitamos asegurarnos
que este sea un objeto TextView.
Bien, la variable es un objeto TextView.
Pero entonces aparece otro error
que dice tipos incompatibles,
porque se requiere un TextView
en el lado derecho,
pero solo encontramos
una vista normal.
Esto es así porque el método findViewById
retorna un View.
¿Cómo podemos reconciliar esto?
Bueno, como TextView es un tipo View
más específico o dicho de otra manera,
un TextView es una subclase
de View, podemos usar
algo llamado casting
(conversión de tipos de datos).
Casting en Java significa que podemos
tomar el View devuelto por este método
y tratarlo como un TextView.
Así que ahora, esto a la derecha
es en realidad un objeto TextView
y luego podemos almacenarlo
en esta variable orderSummaryTextView.
Sé que debe sonar abrumador,
porque acabo de mencionar
muchos nuevos conceptos.
Lo explicaré de nuevo.
El método findViewById
retorna un objeto de tipo View.
Al escribir esta notación,
el tipo de dato deseado del objeto
entre paréntesis,
estamos convirtiendo
este View en un TextView.
Así que toda esta expresión
evalúa un objeto TextView.
Luego, podemos almacenarlo en la variable,
en el lado izquierdo,
que es orderSummaryTextView,
y tiene un tipo TextView.
Ahora, en las líneas siguientes,
podemos llamar a métodos TextView
sobre este objeto.
¿Ves ahora cómo todos los métodos
de texto aparecen aquí?
setAllCaps, setTextSize y más.
Puedo borrar esto ahora,
porque setText debería funcionar,
Y no hay más errores.
Entonces si queremos llamar
a métodos TextView,
necesitamos tener un objeto TextView.
Para tener un objeto TextView,
tenemos que llamar a findViewById,
y luego convertir este objeto View
en un TextView.
La conversión funciona porque
esta vista de la jerarquía de vistas
es en realidad un TextView.
Si tratáramos de convertir algo
como un botón de radio, no funcionaría,
porque orderSummaryTextView
es, en realidad, un TextView,
así que tenemos que convertirlo
en el tipo apropiado.
Del mismo modo, en el método
displayQuantity, llamamos a findViewById
y le pasamos este identificador de recurso
para el TextView quantity.
Esto devuelve un View,
y lo convertimos en un TextView
y podemos almacenarlo dentro de esta
variable llamada quantityTextView.
Esta variable tiene tipo TextView
y entonces,
en líneas siguientes, podemos llamar
a métodos TextView sobre
ella, como setText.
Aquí está el código actualizado
de MainActivity,
usando conversión de tipos.
Podemos convertir estos Views en TextViews
para poder almacenarlos en variables
que tienen tipo TextView.
Entonces, en esta lista
de variables de MainActivity,
ahora quantityTextView y
orderSummaryTextView son de tipo TextView.
Podemos llamar a
métodos TextView sobre estas
y no estamos limitados
a tratarlas solo como Views.
Y ahora podemos llamar
a métodos específicos TextView
sobre estas variables.
Por ejemplo, podemos llamar a setText
sobre orderSummaryTextView
y podemos llamar a setText
sobre quantityTextView.
Como puedes ver, tienes que tener cuidado
sobre qué tipos de datos se usan y dónde.
Hasta ahora, cuando llamamos a métodos,
no nos preocupamos por
el valor de retorno,
porque el método setText,
en realidad, no tiene valor de retorno.
Lo mismo con el método
imageView.setImageResource.
No tiene ningún valor de retorno.
Pero otros métodos pueden
tener valores de retorno.
Por ejemplo, en la clase TextView
tenemos un método getTextSize.
Este retorna un entero,
así que podemos almacenar
el resultado de este método
en una variable llamada size de tipo int.
Aquí hay otro método
que tiene un valor de retorno.
En la clase Button puedes
llamar al método getHeight,
Y este devuelve un valor entero,
por lo que puedes guardarlo
en una variable.
Si trataras de almacenar este resultado
dentro de un string, por ejemplo,
obtendrías un error,
porque este método devuelve un entero.
Para saber qué tipo de datos
debe ser pasado a un método
y qué tipo de datos retorna un método,
debes mirar la documentación.
Por ejemplo, en la clase TextView,
si llamas a cualquiera de estos métodos,
devuelve un valor de tipo int.
El tipo de datos del valor de retorno
está en la columna de la izquierda aquí.
Para otros métodos, podrías obtener
void como valor de retorno, o booleanos,
los que todavía no hemos aprendido,
o floats o longs, etc.
Esta página de documentación
también muestra
cuáles son los tipos de datos esperados
para las entradas de cada método.
Por ejemplo, el método setTextColor
requiere un número entero como entrada
y el valor de retorno es void,
así que no hay valor de retorno.
Entonces mira la documentación para saber
qué tipos de datos se esperan.
De lo contrario, obtendrás errores
en Android Studio
diciendo que los tipos de datos
no coinciden.
Ahora es tu turno para practicar.
Abajo hay cuatro
ejemplos de código diferentes.
Algunos códigos pueden contener errores
relativos a tipos de datos
que no coinciden.
Si encuentras un error,
describe cómo se supone que lo arreglarías
escribiéndolo en las
casillas correspondientes.
De lo contrario,
puedes escribir "no hay error"
si el código está perfectamente bien.
Esta va a ser una prueba exigente
porque acabamos de cubrir
muchos conceptos y este código
todavía es bastante nuevo para ti.
Tómate tu tiempo y mira
la documentación de estos métodos.
Asegúrate que las entradas
y los valores de retorno sean correctos
y que si estamos declarando las variables,
que estén los tipos de datos
correctos aquí.
También, mira la documentación
para estas llamadas a métodos
para asegurar
que usamos
correctamente los métodos.
J'ai ajouté qu'on vient juste
de voir dans notre app.
Ça dit Voir orderSummaryTextView
= findViewById,
alors on passe la ressource ID pour
order_summary_text_view.
Mais ça entraîne une erreur dans
Android Studio sur la prochain ligne.
Ça dit qu'il ne peut résoudre
la méthode setText.
Si j'ajoute une autre
ligne de code ici,
Je peux vous montrer les types de méthodes
qui sont valides sur cette variable.
Donc, on vient juste de créer
la variable orderSummaryTextView ici,
et c'est TypeView,
et donc
sur la prochaine ligne, on devrait
être apte à appeler des méthodes sur ça.
Mais si vous regardez les suggestions
de saisie semi-automatique,
ces méthodes sont en
fait des méthodes de vue.
Il n'y a pas de méthodes
TextView spécifiques.
Par exemple, il n'y a
pas de méthode setText.
C'est pourquoi on a eu une erreur ici
quand on essaye d'appeler setText.
Vous ne pouvez pas non plus établir la taille
du texte ou la couleur du texte ou autre.
Alors où sont toutes ces méthodes?
Bien, a chose est qu'un TextView
est un type de vue plus spécifique.
Alors si on veut appeler les méthodes
TextView
sur cet objet on doit s'assurer
que c'est un objet TextView.
Ok. Maintenant la variable
est un objet TextView.
Mais alors, j'ai une autre erreur qui dit
types incompatibles, car un TextView
est requis sur le côté droit,
mais on trouve juste une vue régulière.
C'est parce que la méthode findViewById
retourne une Vue.
Alors,
comment peut-on concilier cela ?
Eh bien, puisque TextView est un type de vue
plus spécifique ou met une autre façon,
un TextView est une sous-classe de vue,
on peut utiliser une chose appelée casting.
Casting en Java signifie qu'on peut prendre
une Vue retournée par cette méthode et
le traite comme un TextView
Donc maintenant ce côté droit est
est un objet TextView et
alors on peut le stocker dans la
variable orderSummaryTextView.
Je sais que ce doit être vraiment
écrasante parce que je viens de
mentionner une tonne de nouveaux
concepts.
Essayons d'expliquer
encore une fois.
La méthode findViewById retourne
un objet de type Vue.
En écrivant cette notation,
parenthèses avec le type de données de
l'objet désiré dans le milieu de celui-ci.
On va mouler cette
Vue en un TextView.
ALors l'entière expression ici
évalue pour un objet TextView.
Alors, on peut stocker ça dans la variable,
sur le côté gauche,
qui est orderSummary,
et il a un type TextView.
Maintenant, sur les lignes suivantes, on peut
appeler les méthodes TextView sur cet objet.
Voyez-vous maintenant comment toutes les
méthodes de texte font leur apparition ici?
setAllCaps,
setTextSize, et plus.
Donc je peux juste effacer ça maintenant,
car setText devrait fonctionner
et il n'y a plus d'erreur.
Alors si on veut être apte à
appeler les méthodes TextView,
on doit avoir
un objet TextView.
Afin d'avoir un objet TextView,
on doit appeler findViewById,
et puis mouler cet objet Vue
en un TextView.
La raison casting
fonctionne est car
cette Vue ici dans la hiérarchie
de vue est en fait un TextView.
Si on veut le mouler en quelque chose comme
un bouton radio, ça ne fonctionnerait pas,
car le orderSummaryTextView
est en fait un TextView, donc
on doit le mouler en
un type approprié.
Similairement, dans la méthode displayQuantity,
on appelle findViewById et
nous passons dans cette ressource ID
pour la quantité TextView.
Ça retourne une Vue et on
le moule en un TextView et
on peut stocker ça dans cette variable
appelée quantityTextView.
Cette variable est de type
TextView, et alors,
sur les lignes suivantes, on peut appeler les
méthodes TextView dessus, comme setText.
Voici le code mis à jour de l'activité
principal utilisant casting.
On peut mouler ces Vues en TextViews
pour qu'on puisse les stocker dans des
variables de type TextView donc
dans cette liste de l'activité principale,
maintenant quantityTextView et
orderSummaryTextView sont de type TextView.
On peut appler les
méthodes TextView sur cela,
et nous ne sommes pas seulement limités
à les traiter comme des Vues.
Et maintenant on peut appeler les méthodes
TextView spécifiques sur ces variables.
Par exemple, on peut appeler setText
sur le orderSummaryTextView,
et on peut appeler setText
sur le quantityTextView.
Comme vous pouvez voir,
vous devez être prudent sur les
types de données à être utilisés ici.
Jusqu'ici, quand on a appelé des méthodes, on
ne s'est pas inquiété sur la valeur de retour,
car la méthode setText
n'a pas de valeur de retour.
Pareil avec la méthode
imageView.setImageResource.
Ça n'a pas de valeur de retour.
Mais d'autres méthodes peut
avoir des valeurs de retour.
Par exemple, dans la classe TextView
on a une méthode getTextSize.
Ça retourne un entier, donc
on peut stocker le résultat de cette méthode
dans une variable appelé sizeOfTypeInt.
Voici une autre méthode
qui a une valeur de retour.
Dans la classe Button on peut
appeler la méthode getHeight,
et ça retourne une valeur entière, donc
on peut le stocker dans une variable.
Si vous essayez de stocker ce résultat
dans une chaîne, par exemple,
vous obtiendriez une erreur,
car cette méthode retourne un entier.
Afin de savoir quel type de données doit
passer dans une méthode et quel type de
données est retourné par une méthode,
vous devriez vérifier la documentation.
Et par exemple,
dans la classe TextView,
si vous appelez une de ces méthodes,
elle retourne une valeur de type int.
Le type de données de valeur de retour est
sur la colonne de gauche ici.
Pour les autres méthodes, vous pourriez obtenir
vide comme valeur de retour, ou des booléens,
ce qu'on n'a pas encore appris,
ou flottants ou longs etc.
Cette page de documentation page montre
aussi les types de données attendus pour
les entrées pour chaque méthode.
Par exemple, la méthode setTextColor
requiert un entier comme entrée et
la valeur de retour est vide,
donc il n'y a pas de valeur de retour.
Donc vérifiez la documentation pour savoir
quels types de données sont attendus.
Autrement, vous aurez des erreurs
dans Android Studio disant que
les types de données
ne correspondent pas.
Maintenant c'est
votre tour de pratiquer.
En-dessous, il y a quatre différents
exemples de code.
Certain des codes peut contenir des erreurs
liées à la correspondance des types de données.
Si vous trouvez une erreur,
décrivez comment vous êtes supposé le régler
en l'écrivant dans les cases fournies.
Autrement, vous pouvez juste écrire Pas
d'erreur si le code est bon.
Ça va être un quiz difficile
car on vient de couvrir
beaucoup de concepts, et ce code
est toujours assez nouveau pour vous.
Prenez votre temps et vérifiez
la documentation pour ces méthodes.
Assurez-vous que les entrées et les
valeurs de retour soient correctes et
que, si on déclare des variables, qu'on
a les types de données corrects ici.
Aussi,
consultez la documentation pour
les appels de ces méthodes pour s'assurer
qu'on utilise les méthodes correctement.
Saya menambahkan kode yang
baru saja kita lihat ke dalam aplikasi.
Dikatakan Lihat
orderSummaryTextView = findViewById,
maka kita melwati sumber daya ID
untuk order_summary_text_view tersebut.
Tapi ini menyebabkan galat dalam
Android Studio pada baris berikutnya.
Dia mengatakan itu tidak dapat
menyelesaikan metode setText.
Jika saya menambahkan
baris kode lain di sini,
saya dapat menunjukkan jenis metode
yang berlaku pada variabel ini.
Jadi, kita baru saja membuat
variabel orderSummaryTextView di sini,
dan itu adalah TypeView,
dan pada baris berikutnya, kita seharusnya
bisa memanggil metode di atasnya.
Tapi jika kau melihat saran autocomplete,
metode ini sebenarnya metode melihat.
Tidak ada metode TextView tertentu.
Misalnya, tidak ada metode setText.
Benar! Itulah sebabnya kita
mendapatkan galat di sini
saat kita mencoba untuk memanggil setText.
Kau juga tidak dapat mengatur ukuran teks,
atau mengatur warna teks,
atau salah satu dari mereka.
Jadi di mana semua metode itu?
Masalahnya adalah TextView adalah
jenis View yang lebih spesifik.
Jadi jika kita ingin memanggil
metode TextView pada objek ini,
kita perlu memastikan
bahwa ini adalah objek TextView.
Oke. Sekarang variabelnya
adalah objek TextView.
Tapi saya mendapatkan galat lain
yang mengatakan jenis tidak kompatibel,
karena TextView diperlukan di sisi kanan,
tapi kita hanya menemukan tampilan biasa.
Itu karena metode findViewById
mengembalikan sebuah View.
Jadi bagaimana kita mendamaikan ini?
Karena TextView adalah jenis View
yang lebih spesifik atau dengan kata lain,
TextView adalah bagian dari View,
kita dapat menggunakan
sesuatu yang disebut casting [pemilihan].
Casting di Java,
berarti kita dapat mengambil
View dikembalikan oleh metode ini
dan memperlakukannya sebagai
sebuah TextView.
Jadi sekarang sisi kanan ini
sebenarnya objek TextView,
Maka kita dapat menyimpannya di dalam
variabel orderSummaryTextView ini.
Saya tahu kalau ini pasti luar biasa,
karena saya baru saja
menyebutkan banyak konsep baru.
Biarkan saya mencoba
untuk menjelaskannya lagi.
Metode findViewById
ternyata objek tipe View.
Dengan menulis notasi ini,
kurung dengan jenis objek data
yang diinginkan di tengah-tengah itu.
Kami memilih View ini ke TextView.
Jadi seluruh ekspresi di sini
mengevaluasi ke objek TextView.
Kemudian, kita dapat menyimpannya
dalam variabel di sisi kiri,
yang merupakan orderSummary TextView,
dan memiliki tipe TextView.
Sekarang, pada baris berikutnya, kita bisa
memanggil metode TextView pada objek ini.
Apa kau melihat sekarang bagaimana
semua metode teks muncul di sini?
SetAllCaps, setTextSize, dan banyak lagi.
Jadi saya bisa menghapus ini sekarang,
karena setText harus bekerja,
dan tidak ada galat lagi.
Jadi jika kita ingin dapat
memanggil metode TextView,
kita perlu memiliki objek TextView.
Untuk dapat memiliki objek TextView,
Kita perlu memanggil findViewById,
dan kemudian memasukkan View ini
ke objek TextView.
Alasan hal ini bekerja
karena tampilan dalam hirarki
tampilan ini sebenarnya adalah TextView.
Jika kita coba memasukkan sesuatu
seperti tombol radio, itu takkan bekerja,
karena orderSummaryTextView
sebenarnya TextView,
kita harus memasukkannya
ke jenis yang sesuai.
Sama dengan metode displayQuantity,
kita memanggil findViewById
dan kita melewati
sumber ID ke kuantitas TextView.
Ini mengembalikan View,
dan kita memasukkannya ke TextView,
kita dapat menyimpan di dalam variabel
yang disebut quantityTextView.
Variabel ini memiliki tipe TextView,
dan pada baris berikutnya, kita bisa
memanggil TextView metode di atasnya,
seperti setText.
Ini adalah kode MainActivity
yang diperbarui menggunakan casting.
Kita bisa masukkan Views ini ke TextViews,
sehingga kita dapat
menyimpannya dalam variabel
yang memiliki jenis TextView
sehingga dalam daftar
variabel MainActivity,
sekarang quantityTextView dan
orderSummaryTextView adalah tipe TextView.
Kita dapat memanggil
metode TextView pada ini,
dan kita tidak hanya terbatas
untuk memperlakukan mereka sebagai Views.
Dan sekarang kita dapat memanggil metode
TextView tertentu pada variabel tersebut.
Misalnya kita dapat memanggil setText
pada orderSummaryTextView,
dan kita dapat memanggil
setText pada quantityTextView.
Seperti yang kau lihat,
kau harus berhati-hati mengenai
tipe data yang digunakan di mana.
Sejauh ini, saat kita memanggil metode,
kita tidak khawatir tentang nilai kembali,
karena metode setText
sebenarnya tidak memiliki nilai kembali.
Sama dengan metode
imageView.setImageResource.
Ini tidak memiliki nilai kembali.
Tapi metode lain dapat
mempunyai nilai kembali.
Misalnya, di kelas TextView
kita memiliki metode getTextSize.
Ini mengembalikan bilangan bulat,
kita dapat menyimpan hasil dari metode ini
dalam variabel yang
disebut ukuran tipe bilangan bulat.
Ini metode lainnya
yang memiliki nilai kembali.
Di kelas Tombol, kau dapat
memanggil metode getHeight,
dan ini mengembalikan
nilai bilangan bulat,
agar kau dapat
menyimpannya di dalam variabel.
Jika kau mencoba menyimpan hasilnya
di dalam string, misalnya,
kau akan mendapatkan galat, karena
metode ini mengembalikan bilangan bulat.
Untuk mengetahui jenis data
yang perlu diteruskan ke metode
dan jenis data apa yang
kembali dari sebuah metode,
kau harus memeriksa dokumentasinya.
Dan misalnya, di kelas TextView,
jika kau memanggil salah satu metode ini,
dia mengembalikan nilai
tipe bilangan bulat.
Kembalinya nilai tipe data
ada di kolom sebelah kiri di sini.
Untuk metode lain, kau mungkin mendapatkan
kekosongan sebagai nilai kembali,
atau boolean yang belum kita pelajari,
atau mengapung atau panjang dan lain-lain.
Halaman dokumentasi ini juga menunjukkan
menunjukkan tipe data masukan
yang diharapkan untuk setiap metode.
Misalnya, metode setTextColor
membutuhkan bilangan bulat sebagai masukan
dan nilai kembali dibatalkan,
jadi tidak ada nilai kembali.
Jadi periksalah dokumentasi untuk
mengetahui data apa jenis diharapkan.
Jika tidak, kau akan
mendapat galat di Android Studio
dan mengatakan tipe datanya tidak cocok.
Sekarang giliranmu untuk berlatih.
Berikut adalah empat
contoh kode yang berbeda.
Beberapa kode mungkin mengandung galat,
berkaitan dengan tipe data tidak sesuai.
Jika kau menemukan galat,
jelaskan bagaimana kau akan memperbaikinya
dengan menulis di kotak yang disediakan.
Jika tidak, kau dapat menulis tidak ada
galat jika kode ini baik-baik saja.
Ini akan jadi kuis yang menantang
karena kita baru saja menutupi
banyak konsep dan kode ini
masih cukup baru untukmu.
Luangkan waktumu dan memeriksa
dokumentasi untuk metode ini.
Pastikan bahwa masukan
dan nilai kembalinya memang benar.
Bahwa, jika kita menyatakan variabel,
dan kita memiliki jenis data
yang benar di sini.
Juga, mencari dokumentasi
untuk metode panggilan ini,
untuk memastikan kita
memakai metode dengan benar.
このアプリにコードを
追加しました
“View orderSummaryTextView
= findViewById” とあり
“order_summary_text_view” の
リソース ID を渡します
しかし次の行で
エラーがあります
“Cannot resolve the
method setText” と
出ます
行を追加すると
この変数で有効な
メソッド型が出ます
“orderSummaryTextView” の
変数をここに作成します
TypeView なので
次の行でメソッドを
呼び出せるはずです
しかし自動入力の
候補を見ると
これらは全て
View メソッドです
TextView 用のものは
ありません
例えば setText メソッドは
ないので
エラーになり
setText を呼び出しても
テキストのサイズや
色の設定は不可です
ではそのメソッドは
どこでしょう
TextView は特定的な
View の型なので
このオブジェクトで
TextView メソッドを
呼び出すには TextView
オブジェクトであること
今度は変数が
TextView オブジェクトです
しかし普通のビューを
探しているにも拘らず
右側に TextView が必要な為
“型が合わない” と出ました
findViewById メソッドが
View に戻るからです
ではどうやって
一致させるのでしょう
TextView が View の
特定の型ということは
TextView は View のサブクラス
つまりキャストが使えます
Java でのキャストは
このメソッドで
戻った View を TextView
として扱えるので
右側は TextView
オブジェクトで
orderSummaryTextView に
保存できます
新しいことを
多く学んだばかりで
参ってしまいますよね
再度説明します
findViewById メソッドは
View 型のオブジェクトになり
この様に丸括弧して
真ん中にオブジェクトの
データ型を入力します
View を TextView の
中にキャストします
そして TextView オブジェクトを
全ての宣言が評価します
すると左側に
“TextView” 型を持つ
変数 “orderSummary
TextView” が保存できます
下の行では TextView
メソッドが呼び出せます
全てのテキストメソッドが
表示されましたね
setAllCaps や
setTextSize 等があります
setText で大丈夫なはず
なのでこれは消します
エラーが
なくなりました
TextView メソッドの
使用を可能にするには
TextView オブジェクトが
必要になります
TextView オブジェクトには
findViewById が必要なので
View オブジェクトを
TextView にキャストします
キャストが
有効な理由は
ビュー階層の View が
TextView だからです
ラジオボタン等には
キャストできません
“order_summary_text_view”
がTextView だからです
キャストは適切な型に
対して行いましょう
displayQuantity メソッドも同様
“findViewById” を呼び出して
数量 TextView の
リソース ID を渡します
これが View を戻すので
“TextView” にキャストします
すると変数 quantityTextView に
保存できます
この変数には
TextView 型があり
下の行で “setText” 等
TextView が使えます
キャストを使った最新の
MainActivity コードです
TextViews に Views を
キャストして TextViews 型の
変数に保存ができるので
MainActivity のリストでは
“quantityTextView” と
“orderSummaryTextView” は
TextView 型です—これを
TextView メソッドと呼び
Views として扱う
だけでなく
この変数では TextView に
特化したメソッドもあります
orderSummaryTextView で
setText が呼び出せます
また quantityTextView
でも setText が呼び出せます
見ての通り
どのデータ型をどこで
使うか注意が必要です
メソッドを呼び出す時は
setText メソッドに
戻り値がなかったため
気にしませんでした
imageView.setImageResource
メソッドでも同様です
これも戻り値が
ありません
しかし他のメソッドは
どうでしょう
例えば TextView クラスの
getTextSize メソッドは
戻り値が
整数型です
戻り値は int 型の
変数 “size” で保存できます
戻り値のあるメソッドの
もう一つの例です
Button クラスで
getHeight メソッドを
呼び出すと整数値を
戻して変数に保存が可能
もしストリングの中で
結果の保存を試みると
メソッドが整数を戻すので
エラーになります
メソッドに渡すべき
データ型やメソッドから
戻るデータ型を知るには
Documentation を確認します
例えば
TextView クラスでは
これらを呼び出す場合
int 型の値を戻します
戻り値のデータ型は
左の列にあります
他にも戻り値には “void” や
“booleans” もあります
まだ習っていませんが
“floats” “longs” 等もあります
この Documentation は
各メソッドに入力する
データ型も示します
setTextColor メソッドなら
整数の入力が必要です
戻り値は “void” なので
戻り値はありません
Android Studio でデータ型の
不一致のエラーが
出ないようデータ型を
Documentation で
確認しましょう
それでは練習です
これらは4つの異なる
コード例です
いくつかにはデータ型の
不一致のエラーがあります
見つけたら
修正方法をボックスに
書いて下さい
間違いがなければ
“No error” と書いて下さい
多くの新しいコードを
勉強したばかりなので
少々難しいかも
知れません
Documentation を確認しながら
じっくりと解いて下さい
入力内容と戻り値が正しいか
必ず確認しましょう
変数の宣言でデータ型が
正しいか確認しましょう
また正しくメソッドを
使っているか Documentation で
確認しましょう
앱에서 살펴보았던 코드를
추가하였습니다.
View orderSummaryTextView
= findViewById 입니다.
그리고 [order_summary_text_view]에
대한 [resource ID]를 입력합니다.
하지만 이는 다음 행의 안드로이드
스튜디오에서 오류를 발생시킵니다.
[method] [setText]를 실행할 수
없다고 합니다.
이곳에 다른 코드 행을 추가하면,
이 변수에 적합한 [method]의 유형을
보여줄 수 있습니다.
따라서 [orderSummaryTextView]
변수를 이곳에 만듭니다 그리고
이것은 [TypeView]입니다. 따라서 옆
행에서 이에 대한 [methods]를 호출할
수 있습니다.
자동완성 기능을 사용할 경우,
이러한 [methods]는 실질적으로
[View methods]가 됩니다.
[TextView]에 대한 특정 [method]가 없습니다.
예를 들어, [setText] [method]는 없습니다.
따라서 [setText]를 호출하려고 할 때
이곳에서 오류가 발생되는 것입니다.
또한 문자 크기나 색상 등도 설정할 수
없습니다.
이 [method]는 어디에 있습니까?
사실 [TextView]는 더욱 세부적인
유형의 [View] 입니다.
따라서 이 객체에 대한 [TextView] [method]를
호출하고자 한다면, 이것이 [TextView]
객체임을 확인하여야 합니다.
좋습니다.
자 이제 변수는 [TextView] 객체입니다.
하지만 [TextView]는 우측 면에서
작동되고 우리는 단지 일반적인 뷰를
찾기 때문에 호환되지 않는 유형이라는
다른 오류가 발생되었습니다.
이로 인해 [findViewById] [method]가
[View]를 반환하는 것입니다.
어떻게 이를 해결할까요?
[TextView]는 더욱 세부적인 유형의 [View]
이거나 혹은 [TextView]는 뷰의 하위
유형이므로, 실질적으로 캐스팅이라는
것을 사용할 수 있습니다.
자바에서의 캐스팅은 이 [method]에
의해 반환되는 [View]를 갖고 실질적으로
[TextView] 처럼 다룰 수 있음을 의미합니다.
따라서 우측 면은 실질적인 [TextView]
객체이고 이것의 내부에 이
[orderSummaryTextView]의 변수들을
저장할 수 있게 되었습니다.
이미 상당히 많은 새로운 개념들을
언급하였기 때문에 이것이 상당히
어려운 내용임을 알고 있습니다.
다시 한 번 설명해 드리도록 하겠습니다.
[findViewById] [method]는
[type View]의 객체를 반환합니다.
이 [notation]을 적음으로써, 해당 객체의
데이터 유형이 쓰인 괄호들을 중앙에
배열할 수 있습니다.
우리는 이 [View]를 [TextView]로 캐스팅 할 것입니다.
따라서 이곳의 모든 표현들은
[TextView] 객체를 평가하게 됩니다.
그리고, 이를 [orderSummary]
[TextView]인 좌측에 있는 변수에
저장할 수 있고 이는 [type TextView]의
유형을 갖게 됩니다.
다음 행에서, 이 객체에 대한
[TextView] [methods]를 호출할 수 있습니다.
모든 문자 [methods]들이 이곳에
어떻게 나타나는지 확인할 수 있습니까?
[setAllCaps], [setTextSize], 등.
따라서 [setText]가 실행되어야 하기
때문에 이를 지우면 이제 더 이상의
오류는 없습니다.
[TextView] [methods]를 호출하고자 할
경우, [TextView] 객체를 가져야만
합니다.
[TextView] 객체를 갖기 위해,
[findViewById]를 호출하고 이 [View]
객체를 [TextView]로 캐스팅하여야
합니다.
캐스팅 작업의 이유는 뷰 구조 안에
있는 이곳의 [View]가 실질적으로
[TextView]이기 때문입니다.
이를 작동하지 않는 라디오 버튼
등과 같은 무언가로 캐스팅 하고자 할
경우, [orderSummaryTextView]가
실질적인 [TextView]이기 때문에,
적절한 유형으로 캐스팅
하여야 합니다.
이와 같이, [displayQuantity]
[method]에서, [findViewById]를
호출하고 이를 [TextView] 수량에 대한
[resource ID]에 입력합니다.
이는 [View]를 반환합니다. 그리고 이를
[TextView]로 캐스팅하면 이를
[quantityTextView]라는 변수에 저장할
수 있습니다.
이 변수는 [type TextView]를 갖기 때문에
다음 행에서 [setText]와 같이 이에
대한 [TextView] [methods]를 할 수 있습니다.
여기에 업데이트 된 [MainActivity]
코드 사용 캐스팅이 있습니다.
우리는 이 [Views]를 [TextView]로 캐스팅
할 수 있으므로 이것들을 [type TextView]를
가진 변수에 저장합니다. 또한
[MainActivity] 변수들의 목록은 변수들이므로
[now quantityTextView]와 [orderSummary
TextView]는 [type TextView]입니다.
이들에 대한 [TextView] [method]를
호출할 수 있고 이들을 [Views]처럼
다루는 데에 대한 제한은 없습니다.
자 이제 이 변수들에 대한 [TextView]의
특별 [methods]를 호출할 수 있습니다.
예를 들어, [orderSummaryTextView]에
대한 [setText]를 호출할 수 있고
[quantityTextView]에 대한 [setText]를
호출할 수 있습니다.
아시다시피, 어떠한 데이터 유형이
어디에 사용되는지에 관해 주의하여야
합니다.
지금까지, [method]를 호출하였습니다.
[setText] [method]가 실질적으로 반환
값을 가지지 않기 때문에 반환 값에
대해서는 걱정할 필요가 없습니다.
[imageView.setImageResource]
[method]와 같습니다.
여기에 반환 값은 없습니다.
하지만 다른 [method]는
반환 값을 가질 수 있습니다.
예를 들어, [TextView] 클래스에
[getTextSize] [method]를 가지고 있습니다.
이는 정수를 반환합니다. 따라서 [type
int]의 크기로 불리는 변수에 이
[method]의 결과를 저장할 수 있습니다.
여기 반환 값을 가진 다른 [method]가
있습니다.
버튼 클래스에서, [getHeight]
[method]를 호출할 수 있고
이는 정수 값을 반환합니다. 따라서
이를 변수 안에 저장할 수 있습니다.
예를 들어, 문자열 내에 이 결과를
저장하고자 하면 이 [method]는
정수를 반환하기 때문에 오류가
발생될 것입니다.
어떠한 유형의 데이터가 [method]에
입력되고 [method]로부터 어떠한
데이터 유형이 반환되는지를 알기
위해 문서를 확인해 보아야 합니다.
예를 들어, [TextView] 클래스에서,
어떠한 [method]를 호출할 경우,
[type int]의 값이 반환됩니다.
반환 값 데이터 유형은 이곳의 좌측
행에 있습니다.
다른 [method]에 대해,
반환 값 혹은 불 연산자 그리고 아직
배우지 못한 [floats], [longs] 등과
같은 것들을 [void]하여야 할 것입니다.
이 문서 페이지는 또한 각 [method]의
입력 내용에서 어떤 것이 예상되는
데이터 유형인지를 보여줍니다.
예를 들어, [setTextColor] [method]는
입력 내용으로 정수를 요구하고
반환 값이 [void] 됩니다.
따라서 반환 값은 없습니다.
어떠한 데이터 유형이 예상되는지를
알아보기 위해 문서를 확인해 봅시다.
아니면, 안드로이드 스튜디오에 데이터
유형이 일치하지 않습니다 라고
나타내는 오류가 발생될 것입니다.
자 이제 연습해 볼 차례입니다.
아래에 네 개의 다른 코드 예시가 있습니다.
일부 코드는 데이터 유형이 일치하지
않는 것과 관련된 오류를 포함합니다.
오류를 발견하게 되면,
어떻게 이를 수정할 것인지를 아래의
칸에 적어 보십시오.
아니면, 코드에 이상이 없을 경우
오류가 없음을 적을 수 있습니다.
너무나 다양한 개념들을 배웠기
때문에 이는 상당히 어려운 문제가 될
것입니다. 그리고 이 코드는 아직도
당신에게는 새로운 것일 것입니다.
시간을 가지고 이 [method]에 대한
문서를 확인해 보십시오.
입력 내용과 반환 값이 정확한지
확인하시고 변수를 규정할 수 있다면
이곳에 정확한 데이터 유형을 갖게 될
것입니다.
또한 [method]를 정확히 사용할 수
있도록 [method] 호출에 관한 문서를
확인하시기 바랍니다.
Adicionei o código que vimos no nosso app.
Aqui diz View orderSummaryTextView
= findViewById,
então passamos para a ID de recurso para
order_summary_text_view
Mas isso causa um erro na próxima
linha no Android Studio.
Diz "cannot resolve the method setText".
Se eu adicionar uma nova
linha de código aqui,
Posso mostrar os tipos de métodos
válidos nessa variável.
Então, criamos a variável
orderSummaryTextView aqui,
que é uma TypeView, então
na próxima linha, somos capazes
de chamar os métodos nela.
Mas se você vir as sugestões
do autocompletar,
esses métodos, na verdade,
são métodos View.
Não há métodos específicos de TextView.
Por exemplo, não há método setText.
Por isso temos um erro aqui embaixo
quando tentamos chamar setText.
Você também não pode definir o tamanho
ou a cor do texto, ou nada disso.
Então, onde estão todos esses métodos?
O TextView é um tipo mais
específico de View.
Então se quisermos chamar
métodos TextView
neste objeto, precisamos ter certeza
que este é um objeto TextView.
Essa variável é um objeto TextView.
Mas aparece outro erro que diz
incompatible types, porque o TextView
é requerido no lado direito,
mas encontramos apenas um view simples.
Isso porque o método findViewByld
volta para view.
Como resolvemos isso?
Já que TextView é um tipo mais específico
de View, ou melhor,
o TextView é uma subclasse do View,
podemos usar a conversão de tipos.
Conversão em Java significa que podemos
pegar o View de retorno para esse método
e tratá-lo como se fosse um TextView.
Então este lado direito é um
objeto TextView,
e podemos armazená-lo dentro dessa
variável orderSummaryTextView.
Sei que deve ser muita informação,
porque já mencionei
uma tonelada de novos conceitos.
Deixe-me explicar de novo.
O método findViewById torna-se
um objeto do tipo View.
Ao escrever essa notação,
parênteses com os dados do objeto
desejado no meio deles.
Estamos convertendo esse View
em um TextView.
Então toda a expressão aqui vai ser
calculado como um objeto TextView.
Então, podemos armazenar na nossa
variável no lado esquerdo,
onde está orderSummary TextView,
e tem um tipo de TextView.
Nas linhas subsequentes, podemos chamar
os métodos TextView neste objeto.
Estão vendo que agora todos os métodos
de texto estão aqui?
setAllCaps, setTextSize, e outros.
Então posso apagar isso agora,
porque setText deve funcionar,
e não há mais erros.
Então, se quisermos chamar
os métodos TextView,
precisamos ter um objeto TextView.
Para termos um objeto TextView,
precisamos chamar findViewById,
e então converter esse objeto View
em um TextView.
A razão pela qual a conversão
funciona é porque
esse View aqui, na hierarquia do view
é um TextView, na verdade.
Se queremos converter em algo como
um botão de rádio, não vai funcionar,
porque o orderSummaryTextView,
na verdade, é um TextView,
então temos que convertê-lo
no tipo apropriado.
Da mesma forma, no método displayQuantity,
estamos chamando findViewById,
e estamos passando nesse recurso de ID
para a quantidade TextView.
Este retorna como View, e o convertemos
em um TextView, e então,
podemos armazená-lo dentro desta variável
chamada quantityTextView.
Essa variável é do tipo TextView, então,
nas linhas subsequentes, podemos chamar
métodos TextView nela, como o setText.
Aqui está o código da MainActivity
usando a conversão.
Convertemos esses Views em TextViews,
para que sejam armazenados nas variáveis
que tenham o tipo TextView, então nesta
lista das variáveis da MainActivity,
quantityTextView e orderSummaryTextView
são do tipo TextView.
Podemos chamar os métodos TextView,
e não estamos limitados a tratá-los
como Views.
E agora, chamamos os métodos específicos
de TextView nessas variáveis.
Por exemplo, podemos chamar setText
no orderSummaryTextView,
e podemos chamar setText no
quantityTextView.
Como pode ver,
você tem que ter cuidado sobre os tipos
de dados e onde são usados.
Quando chamamos métodos,
não nos preocupamos com o valor de retorno,
porque o método setText não tem
valor de retorno.
Mesma coisa com o método
imageView.setImageResource method,
que não tem valor de retorno.
Mas outros métodos podem ter.
Por exemplo, na classe TextView temos
o método getTextSize.
Isso retorna em uma integral, então
podemos armazenar o resultado deste método
em uma variável chamada size do tipo int.
Um outro método que não tem
valor de retorno.
Na classe Button você pode chamar
o método getHeight,
e isso retorna um valor integral,
então pode-se armazenar na variável.
Se você armazenar esse resultado
dentro de uma cadeia, por exemplo,
vai aparecer um erro, porque esse método
retorna em uma integral.
Para saber que tipo de dados precisam
passar em um método e que tipo
de dados se obtém a partir de um método,
cheque a documentação.
Por exemplo, na classe TextView,
Se você chamar esses métodos,
eles retornam um valor do tipo int.
O valor de retorno do tipo de dados estão
na coluna esquerda.
Para outros métodos, voce pode ter um
valor de retorno inválido, ou booleanos,
que ainda não aprendemos,
ou floats, ou longs, e etc.
Essa página também mostra o que é
esperado de cada tipo de dados
para dar entrada em cada método.
Por exemplo, o método setTextColor requer
uma integral como input
e o valor de retorno é inválido,
então não há valor de retorno.
Cheque o documento para saber que tipos
de dados são exigidos.
Do contrário, você terá erros no Android
Studios que dizem
que os tipos de dados não combinam.
Agora é sua vez de praticar.
Abaixo há quatro exemplos
de códigos diferentes.
Algum deles podem conter erros sobre
os tipos de dados não combinarem.
Se você encontrar o erro,
descreva nas caixas como você consertaria.
Do contrário, você escreve apenas
No error se o código estiver em ordem.
Esse quiz vai ser desafiador porque
tratamos de diversos conceitos,
e esse código é muito novo para você.
Não tenha pressa e cheque os métodos
na documentação.
Tenha certeza que os inputs e os valores
de retorno estejam corretos,
e se declararmos variáveis, que elas
estejam com os tipos de dados corretos.
Também, dê uma olhada na
documentação
sobre esses métodos para ter certeza
que os estamos usando corretamente.
Я добавила код, который мы
выучили, в приложение.
Он гласит View orderSummaryTextView
= findViewById,
затем вводим идентификатор для
order_summary_text_view.
Но это приводит к ошибке в Android
Studio в следующей строке.
Тут говорится, что нельзя решить
метод setText.
Если я добавлю еще одну
строку кода здесь,
я покажу вам типы методов,
действительные в этой переменной.
Мы только что создали переменную
orderSummaryTextView,
и она TypeView, и поэтому
в следующей строке мы сможем
вызывать на нее метод.
Но если взглянуть на предложения
автозаполнения,
эти методы являются методами View.
Нет конкретных методов TextView.
Например, здест нет ни одного
метода setText.
Поэтому мы получаем тут ошибку,
пытаясь вызвать setText.
И вы также не можете задать размер
текста, цвет или что-то из этого.
Так где же все эти методы?
Дело в том, что TextView - более
конкретный тип элемента View.
Поэтому, если мы хотим вызвать
методы TextView на этот объект,
нам надо убедиться, что это объект
элемента TextView.
Итак, переменная является
объектом TextView.
Но появляется другая ошибка: несов-
местимые типы, потому что TextView
должен быть справа, но мы тут видим
только обычный View.
That's because the findViewById
method returns a View.
Как же нам это согласовать?
Раз TextView - более конкретный тип
элемента View или, если по-другому
TextView это подкласс View,
мы можем сделать кое-что c названием
приведение типов. В Java это значит -
мы можем взять View, возвращенный
этим методом,
и считать его за TextView.
Теперь правая сторона является
объектом TextView и
затем можно хранить его внутри этой
переменной orderSummaryTextView.
Знаю, кажется пугающим, потому что
я только что назвала
тонну новых понятий.
Давайте объясню еще раз.
Метод findViewById превращает
объект в тип View.
Записав это обозначение в скобках,
указав в них нужный
тип данных объекта,
мы приводим этот View в TextView.
Таким образом, все выражение здесь
оценивается как объект TextView.
Мы можем хранить это
в переменной слева,
а это orderSummary TextView,
и у него тип TextView.
В последующих строках можно вызвать
на этот объект методы TextView.
Видите, как все текстовые
методы отображаются вот тут?
setAllCaps, setTextSize и другие.
Я могу просто вытереть это потому что
setText должен работать,
а сообщений об ошибках больше нет.
Если мы хотим вызывать
методы TextView,
нам нужно, чтобы был объект TextView.
А чтобі получить обїект TextView,
нужно візвать findViewById,
а затем привести этот объект View
в тип TextView.
Причина, по которо работает
приведение типа, потому что
этот View здесь, в иерархии элемента
является собственно TextView.
Если попытаемся привести его в что-то
вроде радио-кнопки, это не сработает,
потому что orderSummaryTextView
является типом TextView, поэтому
мы должны привести его в
соответствующий тип.
И так же, в методе displayQuantity
мы вызываем findViewById и
вводим идентификатор ресурса
для quantity_Text_View.
Это возвращает View, и мы переводим
его в TextView, и
можем хранить это внутри переменной
под названием quantityTextView.
У этой перменной тип
TextView, и поэтому
в следующих строках мы можем вызвать на
нее методы TextView, например, setText.
Вот обновленный код MainActivity,
использующий приведение типа.
Мы можем привести эти Views в
TextViews, чтобы хранить в переменных
с типом TextView. В этом списке
MainActivity переменных
quantityTextView и orderSummaryTextView
являются типом TextView.
На них мы можем вызывать
методы TextView,
и мы не ограничены тем, чтобы считать
их только типом View.
А теперь мы можем вызвать конкретные
методы TextView на эти переменные.
Например, мы можем вызвать setText
на orderSummaryTextView,
и можем вызвать setText
на quantityTextView.
Как вы видите,
вы должны быть осторожны с тем, какой
тип данных где используется.
До сих пор, когда мы вызывали методы,
не думали о возвращаемой величине,
потому что метод setText вообще-то
не имеет возвращаемой величины.
То же касается и метода
imageView.setImageResource .
У него нет возвращаемой величины.
Но другие методы могут иметь
возвращаемые величины.
Например, в классе TextView есть
метод getTextSize.
Он возвращает целое число, так что
мы можем хранить результат метода в
переменной размер типа int.
А вот еще метод
с возвращаемой величиной.
В этом классе Button [кнопка] вы
можете вызывать метод getHeight,
и он возвращает целое число, которое
вы можете хранить внутри переменной.
Если вам нужно сохранить результат
внутри строки, например,
получите сообщение об ошибке, потому
что метод возвращает целое число.
Чтобы узнать, какой тип данных нужно
вводить в метод и какой тип данных
возвращается назад из метода, вам
нужно свериться с документацией.
А, например, в классе TextView,
если вызвать любой из этих методов,
он возвращает величину типа int.
Тип данных возвращаемой величины
указан в колонке слева.
В других методах можно получить в виде
возвращаемой величины пустого значения
или булевого, которые мы не изучали,
числа с плавающей запятой, длинный
целый тип ... Эта страница документа
показывает расширенные типы данных
для входных значений
для каждого метода.
Например, метод setTextColor требует
целого числа как входного значения,
а возвращаемая величина - void,
так что возвращаемой величины нет.
Поэтому проверяйте описание, чтобы
знать, какие типы данных ожидаются.
В противном случае, будете получать
сообщения об ошибках от
Android Studio о том, что типы
не сопоставимы.
Вернемся к практике.
Внизу четыре разных примера кодов.
Некоторые из кодов
могут содержать ошибки, относящиеся
к несопоставимым типам данных.
Если найдете ошибку,
опишите как ее нужно исправить в
предоставленных внизу окошках.
Если код совершенно верен, можете
просто написать "Ошибок нет".
Этот тест довольно сложный,
потому что мы только что изучили
много понятий и этот код все
еще довольно новый для вас.
Не спешите и сверьтесь с
документацией для этих методов.
Убедитесь, что входные значения и
возвращаемые величины верны,
и что если мы заявляем переменные,
у нас для них верный тип данных.
Также просмотрите
документацию на вызов
этих методов, чтобы убедиться,
что мы используем методы верно.
Aradığımız kodu, uygulamamıza
ekledim.
Kod şu: siparişÖzetiMetinGörünümü
=kimlikleGörünümBul.
sipariş_özet_metin_görünümü
kimlik kaynağını geçiriyoruz.
Fakat bu, Android Studio'da başka
bir hataya neden oluyor.
MetinGir metodu çözülemiyor
deniyor.
Buraya başka bir kod satırı eklersem,
Bu değişken üzerinde geçerli olan
metot türlerini size gösterebilirim.
Burada siparişÖzetiMetinGörünüm
değişkenini ve
VeriTürünü yarattım, böylece
bir sonraki satırda
metotları çağırabiliriz.
Eğer otomatik tamamlama
önerilerine bakarsanız,
Bu metotların, Görünüm metotları
olduğunu görürsünüz.
MetinGörünümü'ne özgü bir metot yok.
Örneğin, metinGir metodu yok.
Bu, metinKur'u çağırdığımızda
hata oluşmasının sebebidir.
Metin boyutunu ya da rengini ya da
herhangi birini giremezsiniz.
Peki bu metotlar nerede?
Pekala, MetinGörünümü
daha spesifik bir Görünüm biçimidir.
Bu yüzden, eğer MetinGörünümü metodunu
bu nesne üzerine çağırırsam, bunun
MetinGörünümü nesnesi o emin olmalıyım.
Tamam. Değişkenimiz şimdi
bir MetinGörünümü nesnesidir.
Fakat sonra başka bir hata, uyumsuz türler
hatasını görüyorum çünkü MetinGörünümü'nün
sağ tarafta olması gerekir fakat
görünümün değişmediğini görüyoruz.
Çünkü kimlikleMetinBul metodu
bir Görünüm döndürüyor.
Bunları nasıl uzlaştırabiliriz?
Pekala, MetinGörünümü daha spesifik bir
Görünüm biçimi ya da
bir altsınıf görünüm olduğu için
döküm dediğimiz şeyi çağırabiliriz.
Java'da dökümün anlamı, bu metot
tarafından döndürülmüş görünümü alıp
bir MetinGörünümü olarak muamele etmektir.
Sağ taraftaki aslında bir MetinGörünümü
nesnesidir ve
siparişÖzetiMetniGörünümü değişkeni
içinde depolayabiliriz.
Bunun gerçekten göz korkutucu olduğunu
biliyorum çünkü bir sürü kavramdan
söz ettik.
Tekrar açıklayayım.
kimlikleGörünümBul metodu, bir Görünüm
verisi nesnesi döndürüyor.
İstenilen veri türü nesnesini,
ortada parantezler içine alarak
yazdığım bu formülle,
bu görünümü MetinGörünümü
içine döküyorum.
Bu ifadenin tümü,
MetinGörünümü nesnesinin değerini verir.
Sonra, sol taraftaki bu değişken
içinde depolayabiliriz ki,
bu değişken siparişÖzetiMetinGörünümü'dür
ve MetinGörünümü türüne sahiptir.
Sonraki satırlarda, MetinGörünümü
metotlarını bu nesne üzerine çağırabiliriz.
Tüm metin metotlarının burada
gösterildiğini görüyor musunuz?
büyükHarfGir, metinBoyutuGir ve
daha fazlası.
Şimdi bunu silebilirim
çünkü MetinGir'in çalışması gerekiyor,
ve artık daha fazla görmüyoruz.
MetinGörünümü metotlarını çağırabilmek
istiyorsak,
bir MetinGörünümü nesnesine
sahip olmalıyız.
Bir MetinGörünümü'ne sahip olmak için,
KimlikleGörünümBul'u çağırmalıyız,
sonra bu Görünüm nesnesini
MetinGörünüm içine dökmeliyiz.
Döküm'ün işlemesinin sebebi
görünüm hiyerarşisindeki bu Görünüm'ün
esas olarak bir MetinGörünümü olmasıdır.
Radyo tuşu gibi bir şeyin içine
dökmeye çalışırsak, çalışmayacaktır
çünkü siparişÖzetiMetniGörünümü
esasen bir Metin Görünümüdür yani
uygun bir tür içine
döküm yapmalıyız.
Benzer şekilde, miktarGöster metodunda,
kimlikleGörünümBul'u çağırıyoruz ve
MetinGörünümü kaynak kimliğini
geçiriyoruz.
Bu, bir Görünüm döndürüyor ve biz de
bunu MetinGörünümü içine döküyoruz ve
böylece bunu miktarMetniGörünümü
değişkeni içinde depolayabiliyoruz.
Bu değişken Metin görünümü türüne sahip,
böylece
takip eden satırlarda, metinGir gibi
MetinGörünümü metotlarını çağırabiliriz.
Burada, döküm'ü kullanan güncellenmiş
AnaAktivite kodunu görüyoruz. Bu görünümü,
MetinGörünümleri’ne dökmek için,
MetinGörünümü türünde olan değişkenlerde
depolayabiliriz böylece
bu AnaAktivite listesindeki
miktarMetinGörünümü ve siparişMetinGörünümü,
MetinGörünümü türü olur.
MetinGörünümü metotlarını bunlar
üzerine çağırabiliriz.
Ayrıca kendimizi bunlara
Görünümler olarak davranmakla sınırlamayız.
Şimdi MetinGörünümü'ne özgü metotları,
bu değişkenler üzerine çağırabiliriz.
Örneğin, metinGir'i sipariş
ÖzetiMetinGörünümü üzerine çağırabiliriz,
metinGir'i miktarMetinGörünümü
üzerine de çağırabiliriz.
Gördüğünüz gibi,
hangi veri türünün, nerede kullanıldığı
konusunda dikkatli olmalısınız.
Şimdiye kadar, metotları çağırdık ve
döndürülen değer konusunda kaygılanmadık
çünkü metinGir metodu esasen
döndürülen bir değere sahip değildir.
Bu, resimGörünümü.resimKaynağıGir
metodu içinde geçerlidir.
Döndürülen bir değer yoktur.
Fakat diğer metotlar döndürülen
değerlere sahip olabilir.
Örneğin, MetinGörünümü sınıfında,
MetinBoyutuEdin metodu vardır.
Bu, bir tamsayı döndürür, böylece
bu metodun sonucunu, tam sayı tür boyutu
değişkeninde depolayabiliriz.
İşte döndürülen değeri olan
başka bir metot.
Tuş sınıfında, yükselikEdin
metodunu çağırabilirsiniz,
bu metot, tam sayı değeri döndürür,
böylece bir değişkende depolayabilirsiniz.
Örneğin, bu sonucu bir dizide depolamayı
deneseydiniz,
hata oluştuğunu görecektiniz
çünkü bu metot tam sayı döndürür.
Ne tür verinin bir metoda geçirilmesi
gerektiğini bilmek ve
bir metottan ne tür verinin döndürüldüğünü
bilmek için dokümantasyonu kontrol edin.
Örneğin, MetinGörünümü sınıfında,
bu metotlardan birini çağırırsanız,
bir tamsayı değeri döndürür.
Döndürülen değer veri türü
sol taraftaki sütundadır.
Diğer metotlarda, geçersiz'i, henüz
öğrenmediğimiz booleları, reel sayıları
ve diğerlerini döndürülen
değer olarak elde edebilirsiniz.
Bu dokümantasyon sayfası,
her metotta kullanılan girdi için beklenen
veri türünü gösteriyor.
Örneğin, metinRengiGir metodu
girdi olarak bir tam sayıyı gerektirir,
döndürülen değer geçersiz'dir
yani döndürülen değer yoktur.
Yani, beklenen veri türünü öğrenmek için
dokümantasyonu inceleyiniz.
Aksi takdirde, veri türlerinin
eşleşmediğini söyleyen
hatalar görürsünüz.
Şimdi sıra sizde.
Aşağıda dört farklı kod örneği var.
Bazı kodlar, veri türünün eşleşmemesi
nedeniyle hata içeriyor olabilir.
bir hata bulursanız,
kutucuklara hataları nasıl
gidereceğinizi yazınız.
Kod çalışıyorsa,
sadece Hayır yazın.
Bu, zorlayıcı bir sınav olacak
çünkü
bir çok kavramdan söz ettik ve
bu kod sizin için oldukça yeni.
Bu metotlar için dokümantasyonu incelemeye
vakit ayırın.
Girdilerin ve döndürülen değerlerin doğru
olduğundan emin olun.
Böylece değişkenler bildirdiğiniz de
doğru veri türleri elde edebilirsiniz.
Metotları doğru kullandığınızdan
emin olmak için de dokümantasyona
göz atınız.
Tôi đã thêm đoạn code chúng ta
đang nhìn thấy đây vào ứng dụng.
Ở đây ghi orderSummaryTextView
= findViewByld,
rồi chuyển ID tài nguyên vào
the order_summary_text_view.
Nhưng có lỗi phát sinh
trong Android Studio hàng tiếp theo.
Báo lỗi là không thể xử lý
phương thức setText.
Nếu tôi thêm một dòng code ở đây.
Tôi sẽ hiển thị các loại phương thức
hợp lệ đối với biến này.
Chúng ta vừa tạo
biến orderSummaryTextView ở đây,
Đó là một TypeView,
trên dòng code tiếp theo,
chúng ta có thể gọi các phương thức này.
Nhưng nếu bạn nhìn vào
các đề xuất điền tự động,
chúng là phương thức hiển thị.
Không có phương thức TextView cụ thể.
Ví dụ, không có phương thức setText.
Đó là tại sao ở đây có lỗi
khi chúng ta gọi setText.
Bạn không thể định kích thước văn bản
màu sắc văn bản, hay các yếu tố khác.
Tất cả các phương thức đó ở đâu?
Vấn đề là một TextView
là một loại hiển thị cụ thể.
Nên nếu muốn gọi các phương thức
trên đối tượng này cần đảm bảo rằng
đây là một đối tượng TextView.
Được rồi.
Bây giờ biến là đối tượng TextView.
Nhưng bây giờ lại có lỗi khác
TextView không tương thích, vì TextView
được yêu cầu ở bên tay phải này,
nhưng chúng ta đang tìm hiển thị thường.
Vì phương thức findViewByld
trả về một hiển thị.
Làm sao xử lý lỗi này?
Vì TextView là một loại hiển thị cụ thể
hay nói cách khác.
TextView là một subclass [lớp con]của hiển
thị chúng ta có thể casting.[ép kiểu]
Casting có nghĩa là qua phương thức này
có thể nhận được hiển thị trả về
và xử lý nó như một TextView.
Bây giờ phía bên phải
là một đối tượng TextView
chúng ta có thể lưu nó bên trong
biến orderSummaryTextView này.
Tôi biết thao tác này
khá khó vì tôi vừa nói
tới rất nhiều khái niệm.
Tôi sẽ giải thích lại.
Phương thức findViewByld trả về
một đối tượng hiển thị nhập liệu.
Bằng cách viết ký hiệu này,
đóng ngoặc loại dữ liệu
đối tượng ở giữa.
Chúng ta ép kiểu hiển
thị này vào TextView.
Vì vậy cả biểu thức này
bằng với một đối tượng TextView.
Sau đó có thể lưu nó trong biến,
ở phía bên tay trái,
đó là TextView orderSummary,
nó có một TextView nhập liệu.
Ở các dòng code tiếp theo có thể gọi các
phương thức TextView trên đối tượng này.
Bạn có thấy bây giờ các phương thức
văn bản được hiển thị ở trên đây không?
SetAllCaps, setTextSize, vân vân.
Tôi có thể xóa cái này đi
vì setText đã vận hành ổn,
không mắc lỗi.
Nếu chúng ta muốn
gọi các phương thức TextView,
phải có một đối tượng TextView.
Để có đối tượng TextView,
Chúng ta cần gọi findViewByld,
và ép kiểu đối tượng hiển thị này
vào trong một TextView.
Ép kiểu có hiệu quả vì
hiển thị này ở trong
phân cấp hiển thị là một TextView.
Nếu ép kiểu nó thành dạng khác
như thành nút chỉnh radio, sẽ không được
vì orderSummaryTextView
là một TextView
nên phải ép kiểu nó vào
loại thích hợp.
Tương tự, trong displayQuantity
gọi phương thức findViewByld
chúng ta chuyển ID tài nguyên vào
trong TextView số lượng.
Nó trả về một hiển thị TextView
chúng ta ép kiểu nó vào TextView
chúng ta có thể lưu bên trong
biến số quantity TextView.
Biến này có TextView nhập liệu,
trên các dòng tiếp theo, chúng ta có thể
gọi phương thức TextView, vd. SetText.
Đây là code cập nhật bởi MainActivity
bằng cách sử dụng ép kiểu.
Có thể ép kiểu các hiển thị vào TextView
để lưu chúng trong biến
có chứa TextView nhập liệu
nên trong danh sách các biến MainActivity
bây giờ quantityTextView
là TextView nhập liệu.
Có thể gọi phương thức TextView cho chúng.
Chúng ta không chỉ giới hạn ở chỗ
có thể xử lý chúng như các hiển thị.
Mà còn có thể gọi
các phương thức TextView trên các biến.
Ví dụ chúng ta có thể gọi setText
trên orderSummaryTextView,
Chúng ta cũng có thể gọi setText
trên quantityTextView.
Như bạn đã thấy,
bạn phải thận trọng xem
loại dữ liệu nào dùng ở chỗ nào thì được.
Tính đến bài này, khi gọi phương thức,
chúng ta không lo lắng về giá trị trả về,
vì phương thức setText
thực sự không có giá trị trả về.
Giống với
phương thức imageView. SetlmageResource.
Nó không có giá trị trả về.
Nhưng các phương thức khác
có thể có giá trị trả về.
Ví dụ, trong lớp TextView
chúng ta có phương thức getTextSize.
Nó trả về một số nguyên,
Có thể lưu kết quả phương thức này
trong biến hằng nguyên kích thước loại
Đây là một phương thức khác
có giá trị trả về.
Trong lớp Button bạn có thể
gọi phương thức getHeight [lấy chiều cao]
Nó trả về một giá trị số nguyên
bạn có thể lưu nó vào biến.
Nếu bạn đã lưu trữ kết quả này
ví dụ như bên trong một chuỗi,
sẽ có báo lỗi
vì phương thức này trả về một số nguyên.
Để biết loại dữ liệu
cần được chuyển vào phương thức
và loại dữ liệu trả về từ phương thức
nên kiểm tra sưu liệu.
Ví dụ, trong lớp TextView,
Nếu gọi một phương thức bất kỳ trong đây
sẽ trả về một giá trị loại int.
Loại dữ liệu trả về
nằm bên cột tay trái ở đây.
Với các phương thức khác, bạn có thể nhận
giá trị trả lại là void [rỗng], boolean.
Boolean thì chúng ta chưa học tới,
hoặc float[chấm động] hoặc kiểu số long.
Trang sưu liệu này cũng hiển thị
các loại dữ liệu cần
để nhập liệu trong mỗi phương thức.
Ví dụ, phương thức setTextColor
đòi hỏi dữ liệu đầu vào là số nguyên
giá trị trả về là void,
vậy không có giá trị trả về.
Hãy kiểm tra sưu liệu để biết
cần loại dữ liệu nào.
Nếu không, sẽ có báo lỗi
từ Android Studio
lỗi dữ liệu không khớp.
Bây giờ đến lượt bạn thực hành.
Dưới đây là 4 ví dụ code khác nhau.
Một số code có thể có lỗi
do loại dữ liệu không tương thích.
Nếu bạn thấy có lỗi,
hãy mô tả cách sửa lỗi
viết ra các ô này.
Ghi là "Không có lỗi"
nếu mã hoàn toàn ổn.
Bài này sẽ khó
vì chúng ta vừa học qua
quá nhiều khái niệm,
code này vẫn còn khá mới mẻ với bạn.
Hãy dành thời gian kiểm tra
sưu liệu cho các phương thức này.
Hãy đảm bảo là các giá trị đầu vào
cũng như các giá trị trả lại chính xác
để khi chúng ta khai báo biến
chúng ta sẽ có loại dữ liệu đúng.
Cũng hay tra cứu sưu liệu
học cách gọi các phương thức này để
dùng phương thức đúng cách.
我把我们刚刚看的代码加入到了应用中
代码是 View orderSummaryTextView = findViewById
然后把资源 ID 传给 order_summary_text_view
但这样的话在 Android Studio 中下一行就会报错
它说无法解析 setText 方法
如果我在这添加另一行代码
它会显示这个变量中有效的方法类型
我们建立一个 orderSummaryTextView 变量
它是一个视图类型
我们能在下一行调用它
如果你看一下自动补全建议
会发现这些方法实际上是视图方法
没有专门针对 TextView 的方法
比如没有 setText 这个方法
这就是我们调用 setText 时会报错的原因
你也不能设置尺寸 颜色 和其他属性
那么那些方法都在哪?
其实 TextView 是一种更加具体的 View
所以如果你想在对象中调用 TextView 方法
我们需要确保这是一个 TextView 对象
现在这个变量是一个 TextView 对象
但是它报错了 它说这个类型不兼容 因为
右边也必须是 TextView 但只找到一个常规 View
因为 findViewById 方法返回的是常规 View
怎么使它们一致呢?
因为 TextView 是一个更具体的 View 换句话说
TextView 是 View 类的一个子类 我们可以使用类型转换
在 Java 中类型转换意味着 我们可以把这个方法返回的 View
转换成一个 TextView
现在 右边已经是个 TextView 对象了
然后把它存到 orderSummaryTextView 变量中
我知道你肯定觉得很迷惑 因为我刚刚
提到了太多新的概念
我们尝试解决一下
findViewById 方法会把对象转化成视图类型
通过写这个标记
也就是括号和里边的对象数据类型
我们就把 View 转换成了 TextView
所以整个表达式计算结果是一个 TextView 对象
然后 我们可以存储到左边的变量里
也就是 orderSummary 里 是 TextView 类型
在下一行 在这个对象中我们可以调用 TextView 方法
你看到展示在这的所有方法了吗?
setAllCaps setTextSize 等等
删除这行 因为 setText 可以工作了
没有报错
如果你想调用 TextView 方法
我们需要有一个 TextView 对象
为了有一个 TextView 对象 我们需要调用 findViewById
然后把 View 转换成 TextView 格式
之所以转换后就可以工作了 是因为
在视图层级结构上这里的这个 View 确实是 TextView
如果我们想转换成其他的 比如单选按钮 就不可以
因为 orderSummaryTextView 是 TextView
我们必须转换成合适的类型
同样 在 displayQuantity 方法中 我们调用 findViewById
把资源 ID 传到 quantityTextView 中
这会返回一个 View 并转化为 TextView
然后存放到 quantityTextView 变量中
这个变量是 TextView 类型 所以
在下一行 我们可以调用 TextView 方法 比如 setText
这是通过类型转换更新的 MainActivity 代码
我们可以把这些 View 转换成 TextView 然后就可以把它们存到
TextView 变量中了 在 MainActivity 变量列表中
现在 quantityTextView 和 orderSummaryTextView 是 TextView 类型
可以用它们调用 TextView 方法
我们不能局限于仅把它们当做 View
现在我们可以用这些变量调用 TextView 专属方法
比如我们可以在 orderSummaryTextView 上调用 setText 方法
在 quantityTextView 上也能调用 setText 方法
正如你看到的
你必须注意在不同地方使用的数据类型
目前为止 在你调用方法时 我们还没考虑过返回值
因为 setText 方法没有返回值
imageView.setImageResource 方法和它一样
没有返回值
但是其他方法可以有返回值
比如在 TextView 类 我们有一个 getTextSize 方法
它会返回一个整型
所以我们可以把结果存到一个叫 size 的整型变量中
这是另一个带返回值的方法
在 Button 类中你可以调用 getHeight 方法
这会返回一个整型 你可以把它存到一个变量里
如果你想把它们存到字符串里
它会报错 因为方法会返回一个整型
为了知道方法中传入的数据类型
和方法返回的数据类型 你需要查阅文档
比如 TextView 类
如果你调用这些方法中的任何一个 就会返回一个整型数值
在左边这一列是返回数据类型
对于其他的方法 你可能会得到空的或布尔类型的返回值
这些我们还没学 还有浮点类型和长整型
这个文档页面还展示了方法所要求的输入
数据类型
比如 setTextColor 方法要求输入整型
返回值是空 所以没有返回值
可以通过查阅文档来了解要求的输入数据类型
否则 Android Studio 就会报错
显示数据类型不匹配
现在该你练习了
这是四个不同的代码示例
有些代码可能出现数据类型不匹配的错误
如果你找到了
在下边的框里写一下如何解决
如果代码是完美的就写上没有错误
这是一个具有挑战性的问题 因为
里边涉及很多概念 这些代码对你来说也很陌生
可以通过查阅文档来学习这些方法
确保输入和返回值是正确的
如果声明变量 数据类型要正确
也可以查阅这些方法的相关文档
来确保正确使用它们
我已經加入剛才我們在應用程式中看到的代碼
這代碼是 View orderSummaryTextView
= findViewById
然后 我們傳入 order_summary_text_view 的資源 ID
但是這會造成下一行在 Android Studio 中發生錯誤
提示說不能解析 setText 方法
如果我在這里新增另外一行代碼
可以顯示對於這個變數有效的方法型式
因此 我們在這里建立 orderSummaryTextView 變數
它是一個 TypeView
因此在下一行 我們應該對它調用方法
但是如果你看這里的自動填入提示
這些方法實際上是 View 方法
并沒有專門用于 TextView 的方法
例如 這里沒有 setText 方法
因此 當我們嘗試調用 setText 時
你也不能設定文字大小 或設定文字顏色或任何其它項
那么所有這些方法在哪里呢
具體來說 TextView 是一種更特殊的檢視圖型別
如果我們想要對這個物件調用 TextView 方法
我們需要確定它是一個 TextView 物件
好的 現在這個變數是一個 TextView 物件
但是我們會看到另外一條錯誤 提示說型別不相容
因為在右側需要一個 TextViewis 檢視圖 但是我們找到的只是一個常規檢視圖
這是因為 findViewById 方法返回一個檢視圖
我們如何解決這個問題呢
由于 TextView 是一種更獨特的檢視圖型式 或者這樣說
TextView 是子類別的檢視圖的 因此我們可以使用一種名為轉型的技術
Java 中的轉型是指我們可以獲取此方法返回的 View
然后實際上將它作為 TextView 進行處理
現在 右側實際上是一個 TextView 物件
然后我們可以將它存放在這個 orderSummaryTextView 變數內
我知道 這確實有點難度 因為我們剛才
講了一大堆的新概念
現在讓我們來嘗試解釋一下
findViewById 方法返回一個 View 類別的型別
書寫這樣的標注
用括弧標注需要的物件資料型別
我們把這個 View 轉型為 TextView.
這樣這里整個運算式的結果就是一個 TextView 物件
然后 我們可把它存放入左側的變數
也就是 orderSummary TextView 它的型別是 TextView
現在 在后面的代碼行 我們可以對這個物件調用 TextView 方法
現在你是否看到所有這有文本方法顯示在這里
setAllCaps, setTextSize 和其他
現在我可以刪除這個 因為 setText 將會發揮作用
而不會有其他的錯誤
因此 如果我們想要調用 TextView 方法
我們需要一個 TextView 物件
為了設定一個 TextView 物件 我們需要調用 findViewById
然后將這個 View 物件轉型為 TextView
這里能夠進行轉型是因為
這個檢視圖階層中的 View 實際上是一個 TextView
如果我們嘗試將它轉型為單選按鈕這樣的物件 它將不會發揮作用
因為 orderSummaryTextView 實際上是一個 TextView
因此我們可以將轉型為適當的型別
同樣地 在 displayQuantity 方法中 我們調用 findViewById
我們為數量 TextView 傳入一個資源 ID
這返回一個 View 我們可以將轉型為 TextView
我們可以將它存放在這個名為 quantityTextView 的變數內
這個變數的型別是 TextView
因此在后面的代碼行 我們可以對它調用 TextView 方法 例如 setText.
這是使用轉型之后 經過更新的 MainActivity 代碼
我們可以把這些檢視圖轉型為 TextViews 這樣我們就可以把它們存放到
TextView 型別的變數 這樣在這個 MainActivity 變數清單中
現在 quantityTextView 和 orderSummaryTextView 是 TextView 型別的
我們可以對它們調用 TextView 方法
我們不僅可以將它們作為 View 進行處理
現在我們還可以對它們調用 TextView 專用方法
例如 我們可以對 orderSummaryTextView 調用 setText 方法
我們可以對 quantityTextView 調用 setText 方法
因此你可以看到
對於在什么位置使用什么資訊型別 你應該十分小心
到目前為止 當我們調用方法時 我們并不需要考慮返回值
因為 setText 方法實際上沒有返回值
imageView.setImageResource 方法也是這樣的
這個方法也沒有返回值
但是其它方法有返回值
例如在 TextView 類別中我們有一個 getTextSize 方法
這個方法返回一個整數
我們可以把這個方法的結果存放到名為 int 型別大小的變數之中
這里有另一個方法 也具有一個返回值
在 Button 類別中 你可以調用 getHeight 方法
這個方法返回一個整數值 因此你可以把它存放在變數中
如果你嘗試把這個結果放在字符串中
85
00:05:06,450 --> 00:05:10,810
將會產生一個錯誤 因為此方法返回一個整數
為了知道需要把哪種型別的資料傳入方法
以及從一個方法返回哪種型別的資料 你需要檢視文檔
例如 在 TextView 類別中
如果你調用這些方法中的任何一個方法 它會返回一個整數型別的值
返回值資料型別位于這里的左側欄
其它方法的返回值可能是 void 或布林值
我們還沒有學習這兩種型的值 另外返回也可能是浮點數或長整數等
這個文件頁還顯示每個方法的輸入變數的
期望資料型別
例如 setTextColor 方法需要整數作為輸入
返回值是 void 因此沒有返回值
讓我們來檢視文件 了解期望什么樣的資料型別
否則 Android Studio 將會報錯
提示資料型別不符合
現在 請你來操練
下面是四個不同的代碼示例
一些代碼可能含有資料型別不符合錯誤
如果你找到錯誤
請在提供的方塊中描述你如何解決這個錯誤
如果代碼是完美的 你可以直接寫出無錯誤字樣
這個測驗有一點難度 因為我們只介紹了幾個概念
而這個代碼對你來說有一點新鮮
請不要著急 查看文件來了解這些方法
保證輸入和返回值是正確的
而且 如果我們要宣告變數 我們需要在這里設定正確的資料型別
另外 請查看這些方法調用的相關文件
確保使用正確的方法