Home » Android » java – OnClickListener for Multiple ImageButton-Exceptionshub

java – OnClickListener for Multiple ImageButton-Exceptionshub

Posted by: admin February 26, 2020 Leave a comment

Questions:

I’m super new in Java! Pardon for this question although there are similar ones but I’m completely clueless on fixing my problem.

I’m trying to set an OnClickListener for each ImageButton to open a new activity.
The first ImageButton works but not for the subsequent ones, it is unclickable in AVD.

Would greatly appreciate some help on it!

public class CharacterSelect extends AppCompatActivity {

ImageButton arrowbtnright;
ImageButton contchibtn;

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

    arrowbtnright = (ImageButton) findViewById(R.id.arrowbtnright);
    contchibtn = (ImageButton) findViewById(R.id.contchibtn);

    arrowbtnright.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            startActivity(new Intent(CharacterSelect.this, CharacterSelect2.class));

            contchibtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startActivity(new Intent(CharacterSelect.this, MiniChallenge1.class));
                }
            });
        }
    });
}
How to&Answers:

You are currently adding the listener of the second button, from inside the listener of the first button, this is probably not what you want to do .

Try putting both at the same level, i.e :

arrowbtnright.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(final View v) {
        startActivity(new Intent(CharacterSelect.this, CharacterSelect2.class));

    }
});

contchibtn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(final View v) {
        startActivity(new Intent(CharacterSelect.this, MiniChallenge1.class));
    }
});