Home > database >  problem with OnClickListener priority in android
problem with OnClickListener priority in android

Time:12-20

I have an app with two buttons. I want first one (main button) to be unclickable unless you click second one (controller). But it is clickable:

public class MainActivity extends AppCompatActivity {
    Button button;
    Button controller;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        LinearLayout screen = findViewById(R.id.mainView);

            button = new Button(this);
            button.setClickable(false);
            screen.addView(button);

            controller = new Button(this);
            screen.addView(controller);

            button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    view.setBackgroundColor(Color.RED);
                }
            });
            controller.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    for (int i=0; i<2; i  ) {
                        button.setClickable(true);
                    }
                }
            });
    }
}

When I implement OnClickListener only for controller, it works and first button is unclickable. But when I implement OnClickListener for main button too, it gets priority and works anyway. What can I do?

CodePudding user response:

Behind the scenes, calling setOnClickListener() makes the target clickable. You can set clickable to false after setting the click listener.

  • Related