简体   繁体   English

我可以从侦听器内部引用 OnClickListener 的按钮吗? (安卓)

[英]Can I reference an OnClickListener's button from inside the listener? (android)

I have an android program where I have multiple buttons using the same OnClickListener, and I want to be able to reference the button's dynamically assigned text from inside the listener.我有一个 android 程序,我有多个按钮使用相同的 OnClickListener,我希望能够从侦听器内部引用按钮的动态分配文本。 Is there some way to reference the button that was pushed to get its text?有没有办法引用被按下以获取其文本的按钮? I don't want to have to make multiple button-specific listeners that do the same thing.我不想让多个特定于按钮的侦听器做同样的事情。

In your onClick(View v) you can cast it to a button:在您的 onClick(View v) 中,您可以将其转换为按钮:

@Override
public void onClick(View v) {
  Button clickedButton = (Button)v;
  // do stuff with it here.
}

use the View which comes as the argument to the onClick(View v)使用作为onClick(View v)参数的 View

this can be casted to a button & worked with.这可以转换为按钮并使用。

The argument to onClick is the View that originated the click, which will be the button to which you attached the listener. onClick 的参数是发起单击的视图,它将是您附加侦听器的按钮。 Cast it to Button to get the button object.将其投射到 Button 以获取按钮 object。

Yes, there should be a way.是的,应该有办法。

public abstract void onClick (View v)

You'll notice that the View that was clicked is passed into the onClick() method.您会注意到被单击的视图被传递到 onClick() 方法中。 So if you have a reference to the View (Button) available (for example, as an instance variable in the Activity) then you can do this:因此,如果您有对可用视图(按钮)的引用(例如,作为 Activity 中的实例变量),那么您可以这样做:

public abstract void onClick (View v) {
    if (v == firstButton) {
        //Do some stuff
    }
    else if (v == secondButton) {
        //Do some other stuff
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Android中的侦听器内的侦听器按钮 - Listener button inside a listener in Android 如何为onClickListener引用按钮? - How to reference button for onClickListener? 如何在IF语句中放置OnClickListener? - How can I put OnClickListener inside IF Statement? 我如何只知道 Button OnClickListener 中的用户 ID 就可以向特定用户发送推送通知? Firebase - How can i send push notification to specific users just knowing the userID inside Button OnClickListener? Firebase Android Studio onClickListener 在 OnClickListener 中尝试调用 null object 参考上的虚拟方法 - Android Studio onClickListener inside an OnClickListener attempt to invoke virtual method on a null object reference 如何从单个侦听器中的按钮组中识别按钮? - How I can recognise button from button group in single listener? Android - 我可以用按钮更改 TextView 的参考吗? - Android - Can I change the reference of a TextView with a button? Android 应用程序按钮 onclicklistener - Android Application Button onclicklistener 无法到达我的OnClickListener函数中的(最终)按钮 - Can't reach my (final) button inside my OnClickListener function 如何从AlertDialog的onClickListener中访问Activity的实例变量? - How can I access my Activity's instance variables from within an AlertDialog's onClickListener?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM