1

在我的 android 应用程序中,我将按钮图像更改 1 秒。有一组按钮。在这 1 秒内,任何一个按钮的图像都会被更改。如果在那 1 秒内单击该特定按钮,我想执行一些操作。我尝试使用 onclick 侦听器,但它不起作用。我怎样才能做到这一点?请帮助我下面是代码 -

protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.next);

myTimer = new Timer();

myTimer.schedule(new TimerTask() {  

@Override
public void run() {
  if(time==-1){

    onStop();
  }
  else
    runOnUiThread(new Runnable() {
    public void run() {

      Random rand=new Random();               
      time=time-1;
      but1=(Button) findViewById(R.id.b1);
      but1.setBackgroundResource(R.drawable.happy);
      but1.setContentDescription("happy");
      but2=(Button) findViewById(R.id.b2);
      but2.setBackgroundResource(R.drawable.happy);
      but2.setContentDescription("happy");

      int num = rand.nextInt(buttonIds.length);
      int buttonId = buttonIds[num];

      Button bb=(Button) findViewById(buttonId);

      if(bb.getContentDescription().equals(button.getContentDescription()))
      {
        bb.setBackgroundResource(R.drawable.happy);
        bb.setContentDescription("happy");
        wrong++;
      }
      else
      {
        bb.setBackgroundResource(R.drawable.whoa);
        count++;

        bb.setContentDescription("whoa");
      }

    }
  });
}

},0, 1000);
}

public void onClick(View v){
//when i clicked on any button its not even entering here
System.out.println("in onlcik............");
int aaa=v.getId();
System.out.println("click id is------------"+aaa);
for(i=0;i<9;i++){
if(aaa==buttonIds[i]){
    findViewById(buttonIds[i]).setOnClickListener(new View.OnClickListener() {

        Drawable dd=findViewById(buttonIds[i]).getBackground();
        public void onClick(View arg0) {
         System.out.println("yes...");

        }
    });
}
}
}

 }
4

2 回答 2

2

看起来您忘记将 onClickListener 添加到您的按钮。

尝试添加

 but1.setOnClickListener(this);
    but2.setOnClickListener(this);

到你的代码。

于 2013-02-11T06:23:15.590 回答
0

为此,您需要buttonObj.setOnClickListener(this);从您的代码中调用。我this在您尝试添加public void onClick(View v)活动时添加了它。implementing View.onClickListner也通过in继承 onClickListner yourActivity

所以你需要两个改变

Class YourActivity extends Activity implements View.onClickListener 

buttonObj.setOnClickListener(this); // must be after initializing buttonObject
于 2013-02-11T06:23:55.200 回答