Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android start activity with onClickListener?

Tags:

java

android

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); 
            }
        });
like image 898
lisovaccaro Avatar asked Jan 10 '13 20:01

lisovaccaro


People also ask

How do you start an 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.


2 Answers

 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);
    }
like image 85
Gridtestmail Avatar answered Oct 05 '22 22:10

Gridtestmail


(findViewById(R.id.button)).setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        startActivity(new Intent(v.getContext(), ACTIVITY.class));
    }
});
like image 21
Mike Brian Olivera Avatar answered Oct 05 '22 23:10

Mike Brian Olivera