简单的方法来setOnClickListener()上的所有活动按钮方法来、按钮、简单、setOnClickListener

2023-09-05 05:05:42 作者:可惜没如果

新到Android的发展,但不完全对Java。眼下的onCreate()方法中我的code是很基本的:

New to android development, but not entirely new to Java. Right now my code inside the onCreate() method is quite basic:

    Button b1 = (Button) findViewById(R.id.button1);
    Button b2 = (Button) findViewById(R.id.button2);
    Button b3 = (Button) findViewById(R.id.button3);
    Button b4 = (Button) findViewById(R.id.button4);
    Button b5 = (Button) findViewById(R.id.button5);
    Button b6 = (Button) findViewById(R.id.button6);
    Button b7 = (Button) findViewById(R.id.button7);
    Button b8 = (Button) findViewById(R.id.button8);
    Button b9 = (Button) findViewById(R.id.button9);
    Button b10 = (Button) findViewById(R.id.button10);
    Button b11 = (Button) findViewById(R.id.button11);
    Button b12 = (Button) findViewById(R.id.button12);
    Button b13 = (Button) findViewById(R.id.button13);
    Button b14 = (Button) findViewById(R.id.button14);
    Button b15 = (Button) findViewById(R.id.button15);
    Button sqrt = (Button) findViewById(R.id.button16);
    Button b17 = (Button) findViewById(R.id.button17);
    Button b18 = (Button) findViewById(R.id.button18);
    Button b19 = (Button) findViewById(R.id.button19);
    Button b20 = (Button) findViewById(R.id.button20);
    b1.setOnClickListener(this);
    b2.setOnClickListener(this);
    b3.setOnClickListener(this);
    b4.setOnClickListener(this);
    b5.setOnClickListener(this);
    b6.setOnClickListener(this);
    b7.setOnClickListener(this);
    b8.setOnClickListener(this);
    b9.setOnClickListener(this);
    b10.setOnClickListener(this);
    b11.setOnClickListener(this);
    b12.setOnClickListener(this);
    b13.setOnClickListener(this);
    b14.setOnClickListener(this);
    b15.setOnClickListener(this);
    sqrt.setOnClickListener(this);
    b17.setOnClickListener(this);
    b18.setOnClickListener(this);
    b19.setOnClickListener(this);
    b20.setOnClickListener(this);

当然,还有一个比这更简单的方法。我试图for循环的简单,但按钮的ID值不符合我的增量。我一定要改变ID值,使这个方法可能,或者是有一个更简单的方法?

Surely there is an easier way than this. I attempted a simple for loop, but the id values of the buttons do not suit an increment of 'i'. Do I have to change the id values to make this method possible, or is there an easier way?

如果是相关的,我使用了最新版本的Andr​​oid SDK的,的Eclipse插件和目标版本号为2.3.3

If it's relevant, I'm using the latest version of the Android SDK, plugin for Eclipse and the target version number is 2.3.3

推荐答案

只是一个有趣的把戏给你,因为你所有的按钮都使用相同的监听器,你可以做这样的事情少code(虽然它不太高效,不太可能,虽然是明显的):

Just a fun trick for you, since all your buttons are using the same listener, you could do something like this with less code (though it's less efficient, not likely to be noticeable though):

ViewGroup group = (ViewGroup)findViewById(R.id.myrootlayout);
View v;
for(int i = 0; i < group.getChildCount(); i++) {
    v = group.getChildAt(i);
    if(v instanceof Button) v.setOnClickListener(this)
}