Toast : it displays a short message (a Toast) on the screen
文章目录
流程
第一步:创建一个Button,命名为Toast(略)
Create a string resource file 的快捷方法:
1.直接在XML file 中编写要输入的文字,会提示黄色,如图
2.Click once on the word "Toast " ,Press Alt-Enter in Windows or Option-Enter in macOS and choose Extract string resource from the popup menu.输入所用的名字 。
第二步:在Button后加入 android:onClick= “showToast”
此时会有red bulb 出现,点击red bulb , Select Create click handler, choose MainActivity, and click OK. 会自动在MainActivity 中创建方法。
(If the red bulb icon doesn’t appear, click the method name (“showToast”). Press Alt-Enter (Option-Enter on the Mac), select Create ‘showToast(view)’ in MainActivity, and click OK.)
// 此处学了一个小技巧,在添加代码的'''之后加入所写代码的简称插入的代码变漂亮[](https://blog.csdn.net/weixin_43295278/article/details/83444960)
<Button
android:id="@+id/button_toast"
android:layout_width="0dp"
...
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:onClick="showToast"/> // 这是加入的一行
第三步:Edit the Toast Button handler
3.1 Locate the newly created showToast() method.
public void showToast(View view) {
}
3.2. To create an instance of a Toast。
call the makeText() factory method on the Toast class.
public void showToast(View view) {
Toast toast = Toast.makeText( //未完待续
}
3.2.1 Supply the context of the app Activity.
Because a Toast displays on top of the Activity UI, the system needs information about the current Activity. When you are already within the context of the Activity whose context you need, use this as a shortcut.
Toast toast = Toast.makeText(this,
3.2.2 Supply the message to display.
such as a string resource (the toast_message you created in a previous step). The string resource toast_message is identified by R.string.
Toast toast = Toast.makeText(this, R.string.toast_message,
3.2.3 Supply a duration for the display.
For example, Toast.LENGTH_SHORT
displays the toast for a relatively short time.The duration of a Toast display can be either Toast.LENGTH_LONG
or Toast.LENGTH_SHORT
. The actual lengths are about 3.5 seconds for the long Toast and 2 seconds for the short Toast.
Toast toast = Toast.makeText(this, R.string.toast_message,
Toast.LENGTH_SHORT);
第四步: Show the Toast by calling show().
The following is the entire showToast() method.
public void showToast(View view) {
Toast toast = Toast.makeText(this, R.string.toast_message,
Toast.LENGTH_SHORT);
toast.show();
}
(完整代码见下一篇 或者 Android developers training)