添加和处理动作(Adding and Handling Actions)

本文详细介绍了如何在Android应用中设置应用栏并添加动作按钮,包括如何定义和显示不同类型的action按钮,以及如何响应用户的操作。通过实例演示了在菜单资源文件中添加action按钮的方法,并展示了如何在activity中处理用户的点击事件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这篇文章是接着上一篇文章翻译的,建议大家先看一看。 设置应用栏(Setting Up the App Bar)

本篇文章的原文地址:
http://developer.android.com/intl/zh-cn/training/appbar/actions.html#handle-actions

不扯别的,开搞

应用栏允许你为了处理用户的动作添加按钮。这个特性允许你把当前界面的最重要的动作的处理放在应用的顶部。

例如一个浏览照片的应用程序会在用户浏览图片列表的时候在应用的顶部展示“分享”和“创建相册”按钮;当用户查看一张照片的时候,应用程序会在顶部展示“剪裁图片”和“滤镜效果”的按钮。应用栏上的空间是有限的。如果actions按钮已经充满了应用栏,这时候用户再声明的acitons按钮会显示在voverflow菜单中。一个应用也可以明确的指出一个action按钮总是在overflow菜单中显示,而不是在应用栏上展示。

这里写图片描述

图表1:只有一个action按钮和一个voerflow菜单的应用栏

添加动作按钮 (Add Action Buttons)

在一个XML 菜单资源文件中定义的action按钮或者其他的item(不一定是按钮,也可能使一个搜索框)都可以在overflow菜单中使用。在你的res/menu/目录下新建一个xml文件来为应用栏添加actions.为每一个你想放入应用栏的item项添加一个元素,如下所示。

<menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <!-- "Mark Favorite", should appear as action button if possible -->
    <item
        android:id="@+id/action_favorite"
        android:icon="@drawable/ic_favorite_black_48dp"
        android:title="@string/action_favorite"
        app:showAsAction="ifRoom"/>

    <!-- Settings, should always be in the overflow -->
    <item android:id="@+id/action_settings"
          android:title="@string/action_settings"
          app:showAsAction="never"/>//永远在overflow中显示

</menu>

app:showAsAction属性指出这个动作item 是否应该在应用栏上以按钮的形式出现。如果你设置了app:showAsAction=”ifRoom”(就像例子中的favorite action设置的那样),这个action 在应用栏上有足够的空间展示的时候,就会展示为一个按钮,如果没有足够的空间,就会被附加到overflow菜单中。如果你设置了app:showAsAction=”never”(就像例子中settings action设置的那样)这个action就会永远出现在overflow菜单中,而不会展示在应用栏上。

当 action被展示在应用栏上的时候,系统会使用这个action的icon来展示这个action。(所以你应该为每一个想在应用栏上展示的action设置一个android:icon=”@drawable/ic_favorite_black_48dp”属性)

你可以在Material Icons页面找到很多有用的图标。(https://design.google.com/icons/

和Actions交互(Respond to Actions)

当用户选择应用栏上的一项时,系统会调用你的activity的onOptionsItemSelected()回调方法,并传递一个MenuItem来指出是哪一项被点击了。在你实现onOptionsItemSelected()的时候,调用 MenuItem.getItemId()来判断是那一项被按下了。返回的ID就是你在对应项的android:id attribute 定义的值。

例如 下列代码用来检查用户选择了那个action。如果这个方法不能识别用户的动作,就会调用父类的方法。

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.action_settings:
            // User chose the "Settings" item, show the app settings UI...
            return true;

        case R.id.action_favorite:
            // User chose the "Favorite" action, mark the current item
            // as a favorite...
            return true;

        default:
            // If we got here, the user's action was not recognized.
            // Invoke the superclass to handle it.
            return super.onOptionsItemSelected(item);

    }
}

接下来我在实践中检验。在res/menu目录下新建一个mymenu.xml
这里写图片描述

mymenu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/action_favorite"
        android:icon="@drawable/ic_favorite_black_48dp"
        android:title="favorite"
        app:showAsAction="ifRoom" />
    <item
        android:id="@+id/action_share"
        android:icon="@android:drawable/ic_menu_share"
        android:title="favorite"
        app:showAsAction="ifRoom" />
<item
    android:id="@+id/action_settings"
    app:showAsAction="never"
    android:title="settings" />
</menu>

</menu>

然后是MainActivity中的方法

 @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        //这句话的意思是把mymenu加载到menu中
        getMenuInflater().inflate(R.menu.mymenu, menu);

        return super.onCreateOptionsMenu(menu);
    }

//处理用户的点击事件
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_share:
                Toast.makeText(this, "我是share action", Toast.LENGTH_SHORT).show();
                return true;
            case R.id.action_favorite:
                Toast.makeText(this, "我是favorite action", Toast.LENGTH_SHORT).show();
                return true;
            case R.id.action_settings:
                Toast.makeText(this, "you click action_settings", Toast.LENGTH_SHORT).show();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

效果图如下:

这里写图片描述

相关的代码没写全是因为在上一篇中也用到了,可以先看一看。对本篇翻译有疑问的欢迎询问。有错误欢迎指出,感激不尽。不能误人子弟啊。

快下班了,赶紧去吃饭,饿死了。

下一篇翻译: 添加一个向前导航的动作(Adding an Up Action)

### 如何为代码添加详细的注释 为代码添加注释是一项重要的实践,它有助于提高代码的可读性可维护性。以下是关于如何为代码添加详细注释的方法: #### 注释的目的 注释的主要目标是解释代码的功能、逻辑以及可能存在的复杂部分。这不仅帮助其他开发者更快地理解代码,还能在未来修改或扩展代码时节省大量时间[^1]。 #### 添加注释的最佳实践 - **函数/方法级注释** 对于每一个函数或方法,应该提供清晰的注释说明其功能、输入参数的意义、返回值的作用以及其他任何需要注意的地方。 - **关键逻辑注释** 如果某段代码实现了复杂的算法或者有特殊的处理方式,则应在相应位置添加注释以便读者了解背后的逻辑。 - **变量定义处注释** 当声明某些特殊用途的变量时,在旁边加上简短描述会很有帮助。 下面是一个具体的例子展示如何为一段Python代码添加详尽的注释: ```python def calculate_average(numbers): """ This function calculates the average of a list of numbers. Parameters: numbers (list): A list containing numerical values. Returns: float: The computed average value from the input list. Note: If 'numbers' is empty, this will raise an exception due to division by zero. Consider adding error handling depending on your use case requirements. """ total_sum = sum(numbers) # Sum all elements within the provided number array. count = len(numbers) # Determine how many items exist inside our dataset. avg_result = total_sum / count # Divide summed result against quantity counted earlier. return avg_result # Return final calculated mean as output back towards caller site. ``` 对于更高级的应用场景比如深度学习模型训练脚本(CycleGAN),也可以参照相似原则进行操作[^2]: ```python import torch.nn as nn class Generator(nn.Module): """Define generator architecture.""" def __init__(self,...): super(Generator,self).__init__() ... self.layers = [...] # Define layers composing neural network structure here def forward(self,x): y = ... # Apply transformations sequentially through defined blocks above return y # Output transformed tensor after passing entire pipeline once more time again finally returns processed image data ready used further processing stages later down stream pipelines accordingly then end up returning generated fake sample outputs based off real ones supplied initially at beginning stage before starting iterative optimization procedures until convergence reached eventually stops updating weights anymore when loss reaches minimum threshold level acceptable enough according specified criteria set forth previously during initialization phase setup procedure steps outlined clearly documented well understood fully implemented correctly without errors occurring anywhere throughout whole process cycle continuously repeating itself over multiple epochs cycles repeatedly consistently producing better quality results each successive iteration pass improving overall performance metrics scores achieved ultimately reaching desired outcome objectives successfully completing task assignment goals originally intended planned out ahead scheduled timeline plans laid beforehand preparation phases leading into execution implementation actions taken place actually happeni
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值