简体   繁体   中英

onClick method doesnt work

protected void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_play);
    gl = (GridLayout) findViewById(R.id.grid);
    array = new Button[7][6];
    Button btn;
    for(int i=0; i<7; i++)
    {
        for(int j=0; j<6; j++)
        {
            btn = new Button(this);
            btn.setId(7*i + j + 1);
            array[i][j] = btn;
            gl.addView(btn);
        }
    }
    turn = 0;
    Toast.makeText(this, "Test", Toast.LENGTH_SHORT).show();                

}

@Override
public void onClick(View v) 
{
    Toast.makeText(this, "Test1", Toast.LENGTH_SHORT).show();               
    if(v instanceof Button)
    {
        Toast.makeText(this, "Test2", Toast.LENGTH_SHORT).show();
        int[] d = GetCellByID(v.getId());
        Button b = (Button)v;
        b.setEnabled(false);
        if(turn == 0)
        {
            b.setBackgroundColor(Color.YELLOW);
            turn = 1;
        }
        else
        {
            b.setBackgroundColor(Color.RED);
            turn = 0;
        }
        array[d[0]][d[1]] = b;
    }
}

This is the code, the Toasts are for testing if what the code is running. The activity implements OnClickListener

The onClick method does not work, I used it because I have 42 buttons and I can't write 42 setOnClickListener() methods for each button.

In the code I create, in two loop, 42 buttons (7*6) and every time each button is pressed it would be disabled and change the background color of the button one time yellow next time red and again.

You are missing to call the following inside the nested for loop:

btn.setOnClickListener(this);

Here, this refers to Activity which implements OnClickListener

set the onClickListner for your button you have missed that.

for(int i=0; i<7; i++)
{
    for(int j=0; j<6; j++)
    {
        btn = new Button(this);
        btn.setId(7*i + j + 1);
        array[i][j] = btn;
        gl.addView(btn);
        btn.setOnClickListener(this);
    }
}

From the code snipper you've posted, I don't see anything linking the onClick method to your button(s).

Try adding

btn.setOnClickListener(this);

into the for-loop

onCreate()中的调用方法

yourButton.setOnClickListener(this);

You must call method in your onCreate()

Try this :

yourbuttonname.setOnClickListener(this);

or

yourbuttonname.setOnClickListener(yourActivity.this);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM