有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java轻松在所有活动按钮上设置setOnClickListener()

对安卓开发来说是新的,但对Java来说并不完全是新的。现在,我在onCreate()方法中的代码非常基本:

    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值不适合“I”的增量。我是否必须更改id值以使此方法成为可能,还是有更简单的方法

如果相关的话,我使用的是Android SDK的最新版本,Eclipse插件,目标版本号是2.3.3


共 (2) 个答案

  1. # 1 楼答案

    一些不那么重复的东西可能是:

    int[] ids = {R.id.button1, R.id.button2, ... };
    for (int id:ids) {
        Button b = (Button) findViewById(id);
        b.setOnClickListener(this);
    }
    
  2. # 2 楼答案

    这对你来说只是一个有趣的把戏,因为你所有的按钮都使用同一个监听器,你可以用更少的代码来做类似的事情(虽然效率较低,但不太可能被注意到):

    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)
    }