How to use the same onClickListener in more than one View?

1

I would like to know the following, I have: ImageButton btneditarusuario; and a TextView editarusuario; , clicking on either one starts startActivity .

How to group ImageButton with TextView so you do not have to repeat the code?

The code:

editarusuario.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    startActivity(new Intent(getApplicationContext(), EditarUsuario.class));
                }
            });

btneditarusuario.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    startActivity(new Intent(getApplicationContext(), EditarUsuario.class));
                }
            });
    
asked by anonymous 06.11.2016 / 17:13

1 answer

3

You have three possibilities:

  • Declare a class that implements the View.OnClickListener

    private class ClickListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
    
            startActivity(new Intent(getApplicationContext(), EditarUsuario.class));
        }
    } 
    

    and pass it to each of the setOnClickListener() :

    ClickListener listener = new ClickListener();
    
    editarusuario.setOnClickListener(listener);
    btneditarusuario.setOnClickListener(listener);
    
  • Make the Activity implement the View.OnClickListener interface

    public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            .....
            .....
    
            editarusuario.setOnClickListener(this);
            btneditarusuario.setOnClickListener(this);
        }
    
        @Override
        public void onClick(View view) {
            startActivity(new Intent(getApplicationContext(), EditarUsuario.class));  
        }
    }
    
  • Use the android:onClick="" attribute with the same method name in the ImageButton and TextView

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        ....
        ....
        android:onClick="startActivityEditarUsuario" />
    
    <ImageButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        ....
        ....
        android:onClick="startActivityEditarUsuario" />
    

    and declare the method in Activity

    public void startActivityEditarUsuario(View view) {
        startActivity(new Intent(getApplicationContext(), EditarUsuario.class));  
    }
    
06.11.2016 / 18:31