【问题标题】:Distinguishing which android button in an array of android buttons was clicked with buttons pointing to a single method使用指向单个方法的按钮区分单击了 android 按钮数组中的哪个 android 按钮
【发布时间】:2013-10-27 10:46:17
【问题描述】:

从这张图片可以看出,我以键盘样式的方式设置了多个按钮。我在 xml 中的每个按钮的 onClick 都指向我的 btnKeyPress 方法。我计划为此方法设置一个开关/案例,但想知道 v.getId 是否是一种非常传统的方式来区分按下哪个按钮并想知道是否有更好的方法。我主要担心无论应用在哪部手机上运行,​​v.getId 是否会根据我的日志发生变化或保持不变。

例如:这是我的 Space 和 Backspace 键的 XML 属性

        <Button
            android:id="@+id/btnKeySpace"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_weight="25"
            android:onClick="btnKeyPress"
            android:text="Space" />

        <Button
            android:id="@+id/btnKeyBackspace"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_weight="75"
            android:onClick="btnKeyPress"
            android:text="Bkspc" />

这就是所谓的

public void btnKeyPress(View v){
    System.out.println(v.getId());
}

【问题讨论】:

    标签: java android xml eclipse adt


    【解决方案1】:

    v.getId() 将始终返回您的布局 xml 中设置的 android:id。所以是的,如果你用它来识别你的按钮,你不会有问题。-

    switch (v.getId()) {
        case R.id.btnKeySpace:
        break;
        case R.id.btnKeyBackspace:
        break;
        // ...
    }
    

    【讨论】:

    • 酷!我的系统返回了一个数字,并打算使用数字来设置我的开关/机箱,但我什至没有意识到我可以这样设置它。只用了一个星期的java。我真是个新手。会尽快接受这个答案。
    • @GarrenFitzenreiter 如果您有疑问,请查看文档developer.android.com/reference/android/view/View.html#getId() 它说它与android:id attribute 有关 =)
    • @ZouZou 谢谢!刚刚开始理解这一切意味着什么。过去 12 年我才知道 vb6,所以我有时会感到困惑。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-12
    • 2011-01-27
    • 2017-06-04
    • 1970-01-01
    • 2012-03-15
    相关资源
    最近更新 更多