使用循环来定义onClickListeners

时间:2014-11-27 19:54:40

标签: android loops onclicklistener

我有以下代码:

        imageButtonArray[0].setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent intent = new Intent(Algebra.this, GeneralSubject.class);
                intent.putExtra("numberOfMovies", numberOfMoviesArray[0]);
                intent.putExtra("titleName", titleNamesArray[0]);
                intent.putExtra("numOfIndex", "0");
                startActivity(intent);
            }
        });

        imageButtonArray[1].setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent intent = new Intent(Algebra.this, GeneralSubject.class);
                intent.putExtra("numberOfMovies", numberOfMoviesArray[1]);
                intent.putExtra("titleName", titleNamesArray[1]);
                intent.putExtra("numOfIndex", "1");
                startActivity(intent);
            }
        });

它工作正常。

当我尝试将该代码更改为:

for (i=0;i<2;i++){
            imageButtonArray[i].setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent intent = new Intent(Algebra.this, GeneralSubject.class);
                intent.putExtra("numberOfMovies", numberOfMoviesArray[i]);
                intent.putExtra("titleName", titleNamesArray[i]);
                intent.putExtra("numOfIndex", String.valueOf(i));
                startActivity(intent);
            }
        });
    }

LogCat说:

  

ArrayIndexOutOfBoundsException:length:2,index:2

这是什么意思?我该如何解决?

1 个答案:

答案 0 :(得分:0)

因为你将i保留为类成员(我的假设是基于我无法在其他地方看到它被宣告为最终的事实)当循环结束时i将是{{1} }。当您点击2

Button

并在您的活动中

  private class MyOnClickListener implements OnClickListener {

       private int mNumberOfMovies;
       private String mTitleName;
       private int mIndex;

       public MyOnClickListener(int numberOfMovies, String titleName, int index) {
               mNumberOfMovies = numberOfMovies;
               mTitleName  = titleName;
               mIndex = index;
       }

       @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Intent intent = new Intent(Algebra.this, GeneralSubject.class);
            intent.putExtra("numberOfMovies", mNumberOfMovies);
            intent.putExtra("titleName", mTitleName);
            intent.putExtra("numOfIndex", mIndex);
            startActivity(intent);
        }
  }