Skip to content Skip to sidebar Skip to footer

Passing Arguments/parameters To Onclicklistener()

I'm new to Android and I'm still trying to wrap my head around some of these concepts, so I'm sorry if I have to ask for frequent clarification. I'm trying to override/create my ow

Solution 1:

Since you already have a View passed to onClick(), no need to also pass an Activity to the enclosing class. Just do:

v.getContext().startActivity(callIntent);

Solution 2:

To start an activity, you need an activity.

One solution is to pass along your activity to your ContactOCL class

public ContactOCL(Activity activity, String contactInfo) {
    this.contactInfo = contactInfo;
    this.activity = activity;
}

Then to start the activity, you use

activity.startActivity(callIntent);

Then when you create this ContactOCL class, you do it by adding the activity parameter, something like: new ContactOCL(this, contactInfo); (I am assuming you create the ContactOCL from your activity class)

Edit: Although my solution works in the general case, for this special case it is not necessary to do it like this since you can access the activity from the view. Instead, see solution suggested by A--C here.

Solution 3:

This class would work as an inner class in an Activity - just drop it in and remove the public class modifier:

publicclassMyActivityextendsActivity
{
    @OverridepublicvoidonCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }

    classContactOCLimplementsOnClickListener {
        String contactInfo;
        publicContactOCL(String contactInfo) {
            this.contactInfo = contactInfo;
        }

        publicvoidonClick(View v) {
            try {
                Intent callIntent = newIntent(Intent.ACTION_CALL);
                callIntent.setData(Uri.parse("tel:" + contactInfo));
                startActivity(callIntent); // No Error here
            } catch (ActivityNotFoundException activityException) {
                Log.e("Calling a Phone Number", "Call failed", activityException);
            }
        }

    }
}

Post a Comment for "Passing Arguments/parameters To Onclicklistener()"