I'm working on a home replacement application. I'm trying to add an OnClickListener
to a button with Java but the way I'm trying produces error:
The method startActivity(Intent) is undefined for the type new View.OnClickListener(){}
This code is inside adapter MyPagerAdapter
.
This is what I am trying:
buttonItem.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent("com.android.contacts.ContactsApplication");
startActivity(intent);
}
});
How can I add an OnClickListener
to a button that opens another application, like for example com.android.contacts.ContactApplication
?
EDIT: This is the full code, with what I am trying right now:
public class MyPagerAdapter extends PagerAdapter {
@Override
public Object instantiateItem(View container, int position) {
Context context = container.getContext();
LinearLayout layout = new LinearLayout(context);
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
TextView textItem = new TextView(context);
Button buttonItem = new Button(context);
buttonItem.setText("Aceptar");
// This is what I'm trying, (crashes on click)
buttonItem.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent("com.android.contacts.ContactsApplication");
v.getContext().startActivity(intent);
}
});
To start an activity, use the method startActivity(intent) . This method is defined on the Context object which Activity extends. The following code demonstrates how you can start another activity via an intent. # Start the activity connect to the # specified class Intent i = new Intent(this, ActivityTwo.
buttonItem.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent();
i.setComponent(new ComponentName("com.android.contacts", "com.android.contacts.DialtactsContactsEntryActivity"));
i.setAction("android.intent.action.MAIN");
i.addCategory("android.intent.category.LAUNCHER");
i.addCategory("android.intent.category.DEFAULT");
v.getContext().startActivity(i);
}
(findViewById(R.id.button)).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(v.getContext(), ACTIVITY.class));
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With