Setting onClickListeners for buttons in scenes programmatically

前端 未结 2 1815
盖世英雄少女心
盖世英雄少女心 2021-01-19 09:23

I have 2 layouts which contain the same buttons

layout_1.xml

  

        
2条回答
  •  终归单人心
    2021-01-19 09:36

    In general, it is not a good idea to have multiple views with the same id. This is what caused the confusion here.

    Note: Below is the solution used by OP that was suitable for their specific needs:

    One simple solution is to use the onClick attribute in the XML file. You can assign the same onClick method to multiple items. Like this:

    And in your activity.java add this:

    public void buttonClicked(View v){
    
        Log.d("TAG","Button clicked!!"
        // do stuff here
    
    }
    

    2nd option:

    When you set a listener for one button with the id of button_1, it does not set the listener for both buttons, it only sets it for the first one. If you want to set the same listener for both, all you need to do is to assign these button different ids and then assign them the same listener.

    This is what you should do:

    Listener myListener = new Listener(){.. blah blah....};
    
    ((Button) findViewById(R.id.some_id)).setListerner(myListener);
    ((Button) findViewById(R.id.some_other_id)).setListerner(myListener);
    

    3rd option:

    findViewById(R.id.id_of_layout1).findViewById(R.id.button_1)
    findViewById(R.id.id_of_layout2).findViewById(R.id.button_1)
    

    in this case, you need add some id to your layout files, for example: layout_1.xml:

    
        

提交回复
热议问题