【问题标题】:button onClick listener. Not entering in onClick function按钮 onClick 监听器。未进入 onClick 功能
【发布时间】:2013-02-11 06:17:36
【问题描述】:

在我的 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...");

        }
    });
}
}
}

 }

【问题讨论】:

    标签: android button onclicklistener


    【解决方案1】:

    您似乎忘记将 onClickListener 添加到您的按钮。

    尝试添加

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

    到您的代码。

    【讨论】:

      【解决方案2】:

      为此,您需要从您的代码中调用 buttonObj.setOnClickListener(this);。 我添加了this,因为您似乎试图在您的活动中添加public void onClick(View v)。也继承了implementingView.onClickListneryourActivity中的onClickListner。

      所以你需要两个改变

      Class YourActivity extends Activity implements View.onClickListener 
      

      buttonObj.setOnClickListener(this); // must be after initializing buttonObject
      

      【讨论】:

        猜你喜欢
        • 2012-02-04
        • 1970-01-01
        • 2012-06-20
        • 2014-04-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-08-16
        相关资源
        最近更新 更多