简体   繁体   中英

how to use onClick function within a condition or calling it in a function? Android

i want to use my PlayerClick(view v) inside a if condition . but it gives me null Exception. it has to retrieve button id.

//Main Code where i wan to call
while (gameLoop > 0){

        while(PlayerClick(null) != 1){

            if( WinnerCheck(currentUser.getSymbolValue()) == 1 || WinnerCheck(currentUser.getSymbolValue()) == 0 ){
                return currentUser;
            }

            if (gameLoop % 2 == 0)
                currentUser = me;
              else
                currentUser = opponent;
        }

        gameLoop--;
    }

Function Is here

 public int PlayerClick(View v) {

//
switch(v.getId()){

            case R.id.btnone:
                     return -1;
            case R.id.btntwo:
                     return -1;
        }
    return 1;
 }

Aim to do this just to pause a while loop while right button is being clicked im using android:onclick = "PlayerClick" for four buttons in XML

i want to use my PlayerClick(view v) inside a if condition . but it gives me null Exception.

Because you are passing null to PlayerClick method.

To get it work you should pass Button view which is pressed by user as parameter in PlayerClick method.

findViewById(android.R.id.yourlayout) pass this in PlayerClick()

like

PlayerClick(findViewById(android.R.id.yourlayout))

Do

button.setOnClickListener(this);

Let your activity implement OnClickListener And when you get onClick(View v) of activity, do as below

@Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
        case R.id.btn_nativex:
            PlayerClick(v);
            break;
        default:
            break;
        }
    }
public int mPlayerClick;

public void PlayerClick(View v) {

    int viewId = v.getId();    
    if (viewId == R.id.btnone) { mPlayerClick = -1; }
    if (viewId == R.id.btntwo) { mPlayerClick = -1; }
    else mPlayerClick = 1;
}

And then.

while (gameLoop > 0){

    while(mPlayerClick != 1){
    ...

I don't understand what you are trying to do though, so this might be wrong. This way mPlayerClick will be set to 1 (and stop your loop) only if the user clicks on some button that is not either btnone or btntwo .

Of course all of your buttons need to call PlayerClick() on click.

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