【Android 学习笔记】Android的基本用法 -Toast & 计数 (1)

原始教程地址

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值