Search code examples
androidandroid-layoutandroid-buttonandroid-event

How to get id of the item clicked from layout action in android?


I am validating the EditText value by clicking anywhere inside the window. But for some buttons, I want to do something different from the validation functionality. How can I get the id of the item from the layout action. Here my layout is ConstraintLayout. Tried the below code but it's not working.

window_layout.setOnClickListener(new 

    View.OnClickListener() {
                @Override
                public void onClick(View v) {
                   
    
                    switch (v.getId()) {
                        case R.id.btn_tech:
                            setButtonsVisibility();
                             break;
                    }
    
                       
                }
            });

Please suggest a better way to implement that.


Solution

  • What you're doing right now is adding the listener to the parent view. You need to set the listener to the individual views.

    You can add a listener variable and add it to the different button views.

    You can also iterate your constraint layout child views and setting the listener individually.

        View.OnClickListener listener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.btn_tech:
                        setButtonsVisibility();
                        break;
                }
            }
        }
    
        for(int i = 0; i <= windowLay.getChildCount(); i++) {
            rec.getChildAt(i).setOnClickListener(listener);
        }