我需要将onClickListener添加到一堆ImageButtons中

时间:2011-06-17 03:12:12

标签: android button onclick listener imagebutton

我在for循环中以编程方式创建了一堆ImageButtons。它们在HorizontalScrollView中显示的数据运行良好。现在我需要每个人在点击时变暗或变亮。首先点击setAlpha(45);第二次单击将setAlpha(255);。

我认为我并不完全理解视图和onClickListener的工作原理。似乎我找到的onClick函数示例采用了View。该函数如何知道单击了哪个按钮?也许有一种更简单的方法来做我想要的事情?

以下是ImageButtons

TableRow tr0 = new TableRow(this);
tr0.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));

for(int but=0; but<ClueList.size(); but++){
   ImageButton clueBut = new ImageButton(this);
      clueBut.setBackgroundResource(0);
      clueBut.setImageBitmap(ClueList.get(but).btmp);
      //clueBut.setOnClickListener(this);

      tr0.addView(clueBut);
}

我是否需要做些什么来使按钮可识别?那将如何传入onClick函数?

- :补充资料: - 我开始怀疑问题不在于按钮,而在于我构建屏幕的方式。添加了更多信息。

游戏活动是主要游戏,它使用PuzzleView作为屏幕上方的游戏网格。下半部分是ImageButtons的位置,我在Game类中将它们构建到位。

public class Game extends Activity{
   //various variables and stuff

   private PuzzleView puzzleView;    // The PuzzleView is from another .java file
                                     // public class PuzzleView extends View

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

      LinearLayout mainPanel = new LinearLayout(this);
      mainPanel.setOrientation(LinearLayout.VERTICLE);

      puzzleView = new PuzzleView(this);
      mainPanel.addView(puzzleView);

      HorizontalScrollView bottom = new HorizontalScrollView(this);
      mainPanel.addView(bottom);

      TableLayout clues = new TableLayout(this);
      bottom.addView(clues);

      TableRow tr0 = new TableRow(this);
      for(int but=0; but<ClueList.size(); but++){
        ImageButton clueBut = new ImageButton(this);
        clueBut.setImageBitmap(ClueList.get(but).btmp);

        tr0.addView(clueBut);
       }

当我尝试添加ClickListener(this)时,我收到有关this无法成为Game的错误。我在引用onClick(View v)的{​​{1}}函数中遇到了类似的问题。这些问题是因为我在Game Activity中构建按钮而不是View类吗?

由于

3 个答案:

答案 0 :(得分:4)

当您设置OnClickListener并实现onClick(View v)回调时,每次单击View时,Dalvik VM都将调用该方法,并且它将View实例作为参数。因此,您在该方法中编写的代码将仅应用于接收到单击的视图,而不应用于任何其他视图。在你的循环中添加这样的东西:

clueBut.setOnClickListener(new OnClickListener() {
  public void onClick (View v) {
    if (v.getAlpha() == 1f)
      v.setAlpha(0.2f);
    else
      v.setAlpha(1f);
  }
});

答案 1 :(得分:1)

在onClick事件中:

public void onClick(View currentView) 
{
    Button currentButton = (Button)CurrentView;
    //Do whatever you need with that button here.
}

答案 2 :(得分:0)

要识别每个视图,请使用属性

  

查看。 SETID(INT)

在您的情况下,代码看起来像这样

for(int but=0; but<ClueList.size(); but++){
   ImageButton clueBut = new ImageButton(this);
      clueBut.setBackgroundResource(0);
      clueBut.setImageBitmap(ClueList.get(but).btmp);
      clueBut.setId(but);
      //clueBut.setOnClickListener(this);

      tr0.addView(clueBut);
}

onclick侦听器内部使用findViewByID()

匹配视图的ID
相关问题