[英]can I have two different onclick methods for one button
我想知道一个按钮是否可以有两个 onclick 方法..我试图有一个按钮可以打开一个新的活动并向服务器发送一个 id 令牌以用于 firebase 目的,如果可能的话,我该怎么做安卓工作室
I think you are getting the underlying concept wrong.我认为你的基本概念是错误的。
Buttons react to clicks.按钮对点击做出反应。
The "ActionListener" that gets triggered on that click ... can do whatever it wants.在点击时触发的“ActionListener”......可以做任何它想做的事情。 There is nothing (conceptually) that prevents you in your code to just trigger various things.
没有什么(概念上)可以阻止您在代码中触发各种事情。 Of course, you have to understand what you are doing (things like: not blocking the UI thread for too long; or how to kick of things in background threads, and so on).
当然,您必须了解自己在做什么(例如:不要长时间阻塞 UI 线程;或者如何在后台线程中启动事物,等等)。
It is one button and so you should apply only one onClick listener which performs the buttons job.它是一个按钮,因此您应该只应用一个执行按钮工作的 onClick 侦听器。
In your onClick-method you can just call another (private) method if you want to do multiple things without sacrificing code management.在您的 onClick 方法中,如果您想在不牺牲代码管理的情况下执行多项操作,则可以调用另一个(私有)方法。
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
sendTokenToServer();
// Include your code to open the activity here or outsource it again into another private method
}
});
And your method to send the token to the server:以及将令牌发送到服务器的方法:
private void sendTokenToServer() {
// Your code here.
}
No. There is only one onClick method for a Button.不可以。一个按钮只有一个 onClick 方法。 But you can still perform two different purposes by one button.
但是您仍然可以通过一个按钮执行两种不同的目的。 I am using a button to hide and show a linear layout.
我正在使用按钮来隐藏和显示线性布局。 The code is given below :
代码如下:
final int[] count = {2};
//here startTopics is the button....
startTopics.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(count[0] %2==0)
{
topicLin.setVisibility(View.VISIBLE);
count[0]++;
}
else
{
topicLin.setVisibility(View.GONE);
//here topicLin is the linear layout
count[0]++;
}
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.