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

Asked

Viewed 448 times

1

I’d like to know the following, I have: ImageButton btneditarusuario; and a TextView editarusuario;, by clicking on either of the two starts the startActivity.

You can group the ImageButton with the TextView to avoid having 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));
                }
            });

1 answer

3


Has three possibilities:

  • Declare a class that implements the interface View.Onclicklistener

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

    and pass it on to each of the setOnClickListener():

    ClickListener listener = new ClickListener();
    
    editarusuario.setOnClickListener(listener);
    btneditarusuario.setOnClickListener(listener);
    
  • Get Activity to implement the interface View.Onclicklistener

    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 attribute android:onClick="" of the same method name, in the declaration of Imagebutton and of 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 the Activity

    public void startActivityEditarUsuario(View view) {
        startActivity(new Intent(getApplicationContext(), EditarUsuario.class));  
    }
    

Browser other questions tagged

You are not signed in. Login or sign up in order to post.