多个按钮的 OnClickListener() android

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25905086/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 09:48:43  来源:igfitidea点击:

Multiple Buttons' OnClickListener() android

androidonclicklistener

提问by user3011685

I'm currently making a simple calculator app on Android. Im trying to set up the code so that when a number button is pressed it updates the calculator screen with that number. Currently I'm doing it like this.

我目前正在 Android 上制作一个简单的计算器应用程序。我试图设置代码,以便在按下数字按钮时它会用该数字更新计算器屏幕。目前我正在这样做。

    Button one = (Button) findViewById(R.id.oneButton);
    one.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            TextView output = (TextView) findViewById(R.id.output);
            output.append("1");
        }
    });

It works but I'm writing this same code for every single button on the calculator. As you can imagine it is very redundant. Is there anyway I can write this code in a more efficient way? One that involves not writing this method for every single button?

它有效,但我正在为计算器上的每个按钮编写相同的代码。你可以想象它是非常多余的。无论如何,我可以以更有效的方式编写此代码吗?一个不是为每个按钮都编写这个方法?

回答by Pragnesh Ghoda シ

You Just Simply have to Follow these steps for making it easy...

您只需按照以下步骤操作即可轻松...

You don't have to write new onClickListenerfor Every Button... Just Implement View.OnClickListerto your Activity/Fragment.. it will implement new Method called onClick()for handling onClick Events for Button,TextView` etc.

您不必onClickListener为 Every Button...编写 new ... 只需实现View.OnClickLister到您的Activity/ Fragment.. 它将实现称为onClick()处理 onClick 事件的新方法Button,TextView` 等。

  1. Implement OnClickListener()in your Activity/Fragment
  1. 实现OnClickListener()你的Activity/Fragment
public class MainActivity extends Activity implements View.OnClickListener {

}
  1. Implement onClick() method in your Activity/Fragment
  1. 在您的 Activity/Fragment 中实现 onClick() 方法
public class MainActivity extends Activity implements View.OnClickListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onClick(View v) {
      // default method for handling onClick Events..
    }
}
  1. Implement OnClickListener()For Buttons
  1. 实现OnClickListener()按钮
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.your_layout);

    Button one = (Button) findViewById(R.id.oneButton);
    one.setOnClickListener(this); // calling onClick() method
    Button two = (Button) findViewById(R.id.twoButton);
    two.setOnClickListener(this);
    Button three = (Button) findViewById(R.id.threeButton);
    three.setOnClickListener(this);

}
  1. Find Buttons By Id and Implement Your Code..
  1. 按 ID 查找按钮并实现您的代码..
@Override
public void onClick(View v) {

    switch (v.getId()) {

        case R.id.oneButton:
            // do your code
            break;

        case R.id.twoButton:
            // do your code
            break;

        case R.id.threeButton:
            // do your code
            break;

        default:
            break;
    }

}

Please refer to this link for more information :

请参阅此链接了解更多信息:

https://androidacademic.blogspot.in/2016/12/multiple-buttons-onclicklistener-android.html

https://androidacademic.blogspot.in/2016/12/multiple-buttons-onclicklistener-android.html

This will make easier to handle many buttons click events and makes it looks simple to manage it...

这将使处理许多按钮单击事件变得更容易,并使管理它看起来很简单......

回答by Andro

You could set the property:

您可以设置属性:

android:onClick="buttonClicked"

in the xml file for each of those buttons, and use this in the java code:

在每个按钮的 xml 文件中,并在 java 代码中使用它:

public void buttonClicked(View view) {

    if (view.getId() == R.id.button1) {
        // button1 action
    } else if (view.getId() == R.id.button2) {
        //button2 action
    } else if (view.getId() == R.id.button3) {
        //button3 action
    }

}

回答by Vadim Novitskiy

I created dedicated class that implements View.OnClickListener.

我创建了实现 View.OnClickListener 的专用类。

public class ButtonClickListener implements View.OnClickListener {

    @Override
    public void onClick(View v) {
        Toast.makeText(MainActivity.this, "Button Clicked", Toast.LENGTH_SHORT).show();
    }

}

Then, I created an instance of this class in MainActivity

然后,我在 MainActivity 中创建了这个类的一个实例

private ButtonClickListener onClickBtnListener = new ButtonClickListener();

and then set onClickListener for button

然后为按钮设置 onClickListener

btn.setOnClickListener(onClickBtnListener);

回答by Henrik Christensen

Set a Tag on each button to whatever you want to work with, in this case probably an Integer. Then you need only one OnClickListener for all of your buttons:

将每个按钮上的标签设置为您想要使用的任何内容,在这种情况下可能是一个整数。那么你的所有按钮只需要一个 OnClickListener :

Button one = (Button) findViewById(R.id.oneButton);
Button two = (Button) findViewById(R.id.twoButton);
one.setTag(new Integer(1));
two.setTag(new Integer(2));

OnClickListener onClickListener = new View.OnClickListener() {

    @Override
    public void onClick(View v) {
        TextView output = (TextView) findViewById(R.id.output);
        output.append(v.getTag());
    }
}

one.setOnClickListener(onClickListener);
two.setOnClickListener(onClickListener);

回答by Henrik Christensen

public class MainActivity extends AppCompatActivity implements OnClickListener  {
    Button  b1,b2;
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        b1= (Button) findViewById(R.id.button);
        b2= (Button) findViewById(R.id.button2);
        b1.setOnClickListener(this);
        b2.setOnClickListener(this);
    }


    @Override
    public void onClick(View v)
    {
        if(v.getId()==R.id.button)
        {
            Intent intent=new Intent(getApplicationContext(),SignIn.class);
            startActivity(intent);
        }
        else if (v.getId()==R.id.button2)
        {
            Intent in=new Intent(getApplicationContext(),SignUpactivity.class);
            startActivity(in);
        }
    }
}

回答by vicky mahale

Implement onClick() method in your Activity/Fragment public class MainActivity extends Activity implements View.OnClickListener {

在您的 Activity/Fragment 公共类 MainActivity 中实现 onClick() 方法扩展 Activity 实现 View.OnClickListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onClick(View v) {
 switch (itemId) {

// if you call the fragment with nevigation bar then used.

           case R.id.nav_menu1:
                fragment = new IntroductionFragment();
                break;

// if call activity with nevigation bar then used.

            case R.id.nav_menu6:
                Intent i = new Intent(MainActivity.this, YoutubeActivity.class);
                startActivity(i);
      // default method for handling onClick Events..
    }
}

回答by Sazidur Rahman

public void onClick(View v) {
    int id = v.getId();
    switch (id){
        case R.id.button1:
            //do ur code
            Toast.makeText(this,"This is button 1",Toast.LENGTH_SHORT).show();
            break;
        case R.id.button2:
            Intent intent = new Intent(this,SecondActivity.class);
            Intent.putExtra("key",value);
            startActivity(intent);
            break;
        case R.id.button3:
            //do ur code
            break;
        case R.id.button4:
            //do ur code;
            break;
        default:
            //do ur code;
    }
}

回答by user3905781

You can use this

你可以用这个

    TextView output = (TextView) findViewById(R.id.output);
    one.setOnClickListener(youractivity.this);
    // set the onclicklistener for other buttons also

    @Override
    public void onClick(View v) {
      int id = v.getId();
    switch(id) {
    case R.id.oneButton:      
       append("1",output);
       break;
    case R.id.twoButton:
        append("2",output);
       break;
    case R.id.threeButton:
        append("3",output);
       break;
     } 
      }

 private void append(String s,TextView t){
  t.setText(s); 
}

you can identify the views in your activity in a separate method.

您可以在单独的方法中识别您的活动中的视图。

回答by Akshit Agarwal

I had a similar issue and what I did is: Create a array of Buttons

我有一个类似的问题,我所做的是:创建一个按钮数组

Button buttons[] = new Button[10];

Then to implement on click listener and reference xml id's I used a loop like this

然后在单击侦听器上实现并引用 xml id,我使用了这样的循环

for (int i = 0; i < 10; i++) {      
String buttonID = "button" + i;
        int resID = getResources().getIdentifier(buttonID, "id",
                "your package name here");
        buttons[i] = (Button) findViewById(resID);
        buttons[i].setOnClickListener(this);
    }

But calling them up remains same as in Prag's answer point 4. PS- If anybody has a better method to call up all the button's onClick, please do comment.

但是调用它们与 Prag 的回答点 4 中的相同。 PS-如果有人有更好的方法来调用所有按钮的 onClick,请发表评论。

回答by mholberger

I find that using a long if/else chain (or switch), in addition to the list of findViewById(btn).setOnClickListener(this)is ugly. how about creating new View.OnlickListeners with override, in-line:

我发现使用长的 if/else 链(或 switch),除了列表findViewById(btn).setOnClickListener(this)是丑陋的。如何创建带有覆盖的新 View.OnlickListeners,内嵌:

findViewById(R.id.signInButton).setOnClickListener(new View.OnClickListener()
    { @Override public void onClick(View v) { signIn(); }});
findViewById(R.id.signOutButton).setOnClickListener(new View.OnClickListener()
    { @Override public void onClick(View v) { signOut(); }});
findViewById(R.id.keyTestButton).setOnClickListener(new View.OnClickListener()
    { @Override public void onClick(View v) { decryptThisTest(); }});
findViewById(R.id.getBkTicksButton).setOnClickListener(new View.OnClickListener()
    { @Override public void onClick(View v) { getBookTickers(); }});
findViewById(R.id.getBalsButton).setOnClickListener(new View.OnClickListener()
    { @Override public void onClick(View v) { getBalances(); }});