OnClick method not working

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, Toasts are for testing if the code works. Activity implementsOnClickListener

The method onClick

doesn't work, I used it because I have 42 buttons and I cannot write 42 setOnClickListener()

for each button.

In the code I am creating in two loops 42 buttons (7 * 6) and every time each button is clicked it will be disabled and change the background color of the button once to yellow, next time to red and again.

+3


source to share


5 answers


You don't need to call the following inside your nested loop for

:

btn.setOnClickListener(this);

      



Here this

refers to Activity

which implementsOnClickListener

+6


source


set onClickListner for your button you missed.



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);
    }
}

      

+6


source


From the frame code of the code you posted, I don't see anything linking the onClick method to your buttons.

Try adding

btn.setOnClickListener(this);

      

in the for-loop

+4


source


Calling a method in your onCreate ()

yourButton.setOnClickListener(this);

      

+4


source


You have to call the method in your onCreate ()

Try the following:

yourbuttonname.setOnClickListener(this);

      

or

yourbuttonname.setOnClickListener(yourActivity.this);

      

0


source







All Articles