Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Common class for click listener

I have 7 buttons in all my 6 activities. All 6 buttons have the same functionality in all activities. How can I perform a common click event lisnter for these 6 buttons.

like image 576
URAndroid Avatar asked Jun 01 '13 07:06

URAndroid


2 Answers

Putting more words in Sagar's answer given above.

Assumption:

As you have said you have 7 buttons in your 6 activities, I assume all the 7 buttons have same functionality/code.

Solution:

Step 1: Include android:click="btnFirstClick" in <Button> inside your XML layouts.

Step 2: Define abstract BaseActivity class by extending Activity and include methods with the same name you have given in android:onClick attribute.

abstract public class BaseActivity extends Activity {

   /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
   }

   public void btnFirstClick(View v) {
   }

   public void btnSecondClick(View v) {
   }

   .....
   .....
  // same for other buttons
}

Step 3: Now extends this BaseActivity to all your 6 activities.

For example:

public class FirstActivity extends BaseActivity {

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState); 
           setContentView(R.layout.layout_first);
    }
}
like image 134
Paresh Mayani Avatar answered Oct 05 '22 23:10

Paresh Mayani


You can create a new class that implements View.OnClickListener like this:

public class MyClickListener implements View.OnClickListener {
    @Override
    public void onClick(View view) {
         // TODO handle the click   
    }
}

In all your activities you can then set the click listener like this:

button.setOnClickListener(new MyClickListener());

You could even save the context in the class for displaying Toasts etc.

public class MyClickListener implements View.OnClickListener {
    private Context context;

    public MyClickListener(Context context) {
        this.context = context;
    }

    @Override
    public void onClick(View view) {
         Button button = (Button) view;
         Toast.makeText(this.context, button.getText().toString(), Toast.LENGTH_SHORT).show();
    }
}
like image 40
koesie10 Avatar answered Oct 06 '22 01:10

koesie10