Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 37 You must be signed in to star a gist
  • Fork 25 You must be signed in to fork a gist
  • Save udacityandroid/d5826cdde2e0591c0162452f48f6be2d to your computer and use it in GitHub Desktop.
Save udacityandroid/d5826cdde2e0591c0162452f48f6be2d to your computer and use it in GitHub Desktop.
Use OnClickListeners for All Categories - onCreate method in MainActivity.java
// Find the View that shows the numbers category
TextView numbers = (TextView) findViewById(R.id.numbers);
// Set a click listener on that View
numbers.setOnClickListener(new View.OnClickListener() {
// The code in this method will be executed when the numbers View is clicked on.
@Override
public void onClick(View view) {
Intent numbersIntent = new Intent(MainActivity.this, NumbersActivity.class);
startActivity(numbersIntent);
}
});
@yuri117
Copy link

yuri117 commented Dec 22, 2018

Very smart solution, @ZetFury. Congrats!

@a7bekjnoon
Copy link

/*

  • Copyright (C) 2016 The Android Open Source Project
  • Licensed under the Apache License, Version 2.0 (the "License");
  • you may not use this file except in compliance with the License.
  • You may obtain a copy of the License at
  •  http://www.apache.org/licenses/LICENSE-2.0
    
  • Unless required by applicable law or agreed to in writing, software
  • distributed under the License is distributed on an "AS IS" BASIS,
  • WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  • See the License for the specific language governing permissions and
  • limitations under the License.
    */
    package com.example.android.miwok;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Set the content of the activity to use the activity_main.xml layout file
    setContentView(R.layout.activity_main);

    //Find the view which shows the numbers category
    TextView numbers = (TextView) findViewById(R.id.numbers);

//Set a click listener on that view
numbers.setOnClickListener(new View.OnClickListener() {
// The code in this method will be called when the numbers view is clicked on.
@OverRide
public void onClick(View view) {
Intent numbersIntent = new Intent(MainActivity.this, NumbersActivity.class);
startActivity(numbersIntent);
}

    });

    //Find the view which shows the family category.
    TextView family = (TextView) findViewById(R.id.family);

//Set a click listener on that view.
family.setOnClickListener(new View.OnClickListener() {
//The code in this method will be called when the family view is clicked on.
@OverRide
public void onClick(View view) {
Intent familyIntent = new Intent(MainActivity.this, FamilyActivity.class);
startActivity(familyIntent);
}
});

    //Find the view which shows the colors category.
    TextView colors = (TextView) findViewById(R.id.colors);

//Set a click listener on that view.
colors.setOnClickListener(new View.OnClickListener() {
//The code in this method will be called when the colors view is clicked on.
@OverRide
public void onClick(View view) {
Intent colorsIntent = new Intent(MainActivity.this, ColorsActivity.class);
startActivity(colorsIntent);
}
});

    //Find the view which shows the colors category.
    TextView phrases = (TextView) findViewById(R.id.phrases);

//Set a click listener on that view.
phrases.setOnClickListener(new View.OnClickListener() {
//The code in this method will be called when the colors view is clicked on.
@OverRide
public void onClick(View view) {
Intent phrasesIntent = new Intent(MainActivity.this, PhrasesActivity.class);
startActivity(phrasesIntent);
}

    });
}

}

@MikeySmash
Copy link

I love this onClickListener solution by @rzettervall : https://gist.github.com/udacityandroid/d5826cdde2e0591c0162452f48f6be2d#gistcomment-2755339

menuClick(findViewById(R.id.numbers),this,NumbersActivity.class);
menuClick(findViewById(R.id.phrases),this,PhrasesActivity.class);
menuClick(findViewById(R.id.colors),this,ColorsActivity.class);
menuClick(findViewById(R.id.family),this,FamilyActivity.class);
}

private void menuClick(View v, final Context context, final Class target) {
v.setOnClickListener(new View.OnClickListener() {
@OverRide
public void onClick(View view) {
Intent i = new Intent(context,target);
startActivity(i);
}
});

I've adapted it using @felipisan shortened version to get this:

    // Finds correct view and sets the target for menuClick
    menuClick(findViewById(R.id.imageNumbers),this,numbers.class);
    menuClick(findViewById(R.id.imagePhrases),this,phrases.class);
    menuClick(findViewById(R.id.imageColour),this,colours.class);
    menuClick(findViewById(R.id.imageFamily),this,family.class);
}
// Sets the on click listener using appropriate target then opens this activity
private void menuClick(View v, final Context context, final Class target) {
    v.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            startActivity(new Intent(context,target));
        }
    });

@sheikhrasik
Copy link

I created the intents as directed in the video in the onClick() method. The app runs just fine but once i click the textViews on my device it doesn't move to the particular activity.For example if i click the numbers text view it should shift to the numbers activity but it does nothing at all. Please help

public void opensNumbersList(View v) {
// Find the View that shows the numbers category
TextView numbers = (TextView) findViewById(R.id.numbers);

    // Set a click listener on that View
    numbers.setOnClickListener(new View.OnClickListener() {
        // The code in this method will be executed when this view is clicked on.
        @Override
        public void onClick(View v) {
           Intent numbersIntent = new Intent(MainActivity.this , NumbersActivity.class);
            startActivity(numbersIntent);
        }
    });
}

@xMagicXs
Copy link

xMagicXs commented Sep 9, 2019

this worked for me

// Find the View that shows the numbers category
TextView numbers = (TextView) findViewById ( R.id.numbers );

// Set a click listener on that View
if ( numbers !=null){
//Set a click listener on that View
numbers.setOnClickListener ( new View.OnClickListener () {
//The code in this method will be executed when the family View is clicked on.
@OverRide
public void onClick(View v) {
Intent numbersIntent = new Intent ( MainActivity.this, NumbersActivity.class );
startActivity ( numbersIntent );
}
} );
}
//Find the view that shows family cathegory
TextView family = (TextView)findViewById ( R.id.family );

    //Set a click listener on that View
    if ( family != null){
        family.setOnClickListener ( new View.OnClickListener () {
            //The code in this method will be executed when the family View is clicked on.
            @Override
            public void onClick(View v) {
                Intent familyIntent = new Intent ( MainActivity.this, FamilyActivity.class );
                startActivity ( familyIntent );
            }
        } );
    }
    //Find the view that shows colors cathegory
    TextView colors = (TextView) findViewById ( R.id.colors );

    //Set a click listener on that View
    if (colors != null){
        colors.setOnClickListener ( new View.OnClickListener () {
            //The code in this method will be executed when the colors View is clicked on.
            @Override
            public void onClick(View v) {
                Intent colorsIntent = new Intent ( MainActivity.this, ColorsActivity.class );
                startActivity ( colorsIntent );
            }
        } );
    }
    //Find the view that shows phrases cathegory
    TextView phrases = (TextView) findViewById ( R.id.phrases );

    //Set a click listener on that View
    if ( phrases != null){
        phrases.setOnClickListener ( new View.OnClickListener () {
            //The code in this method will be executed when the phrases View is clicked on.
            @Override
            public void onClick(View v) {
                Intent phrasesIntent = new Intent ( MainActivity.this, PhrasesActivity.class );
                startActivity ( phrasesIntent );
            }
        } );
    }
}

@lak4ever
Copy link

I created the intents as directed in the video in the onClick() method. The app runs just fine but once i click the textViews on my device it doesn't move to the particular activity.For example if i click the numbers text view it should shift to the numbers activity but it does nothing at all. Please help

public void opensNumbersList(View v) {
// Find the View that shows the numbers category
TextView numbers = (TextView) findViewById(R.id.numbers);

    // Set a click listener on that View
    numbers.setOnClickListener(new View.OnClickListener() {
        // The code in this method will be executed when this view is clicked on.
        @Override
        public void onClick(View v) {
           Intent numbersIntent = new Intent(MainActivity.this , NumbersActivity.class);
            startActivity(numbersIntent);
        }
    });
}

(new View.OnClickListener() please look carefully with this part is it new view or something else?

@mudasiri
Copy link

Why do we pass (MainActviity,this, NumbersActivity,class) instead of (this, NumbersActivity.class)

That's because MainActivity.this - is specifying the context clearly. When you are in an inner function it's best to state the context class fully rather than just using the 'this'. thus to help solve any issues that hans to do with scope resolutions.

@seghier
Copy link

seghier commented Nov 20, 2019

This work fine

package com.example.android.miwok;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Set the content of the activity to use the activity_main.xml layout file
        setContentView(R.layout.activity_main);

        //attach the listener to the view
        TextView numbers = (TextView)findViewById(R.id.numbers);
        numbers.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent numbersIntent = new Intent(MainActivity.this,NumbersActivity.class);
                startActivity(numbersIntent);
            }
        });
        TextView colors = (TextView)findViewById(R.id.colors);
        colors.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent colorsIntent = new Intent(MainActivity.this,ColorsActivity.class);
                startActivity(colorsIntent);
            }
        });
        TextView family = (TextView)findViewById(R.id.family);
        family.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent familyIntent = new Intent(MainActivity.this,FamilyActivity.class);
                startActivity(familyIntent);
            }
        });
        TextView phrases = (TextView)findViewById(R.id.phrases);
        phrases.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent phrasesIntent = new Intent(MainActivity.this,PhrasesActivity.class);
                startActivity(phrasesIntent);
            }
        });

    }

}

@HMVinueza
Copy link

I want to share my version of the code:

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Set the content of the activity to use the activity_main.xml layout file
    setContentView(R.layout.activity_main);

    //Number Listener
    setListenerOpenActivity(findViewById(R.id.numbers),NumbersActivity.class);
    setListenerOpenActivity(findViewById(R.id.colors),ColorsActivity.class);
    setListenerOpenActivity(findViewById(R.id.phrases),PhrasesActivity.class);
    setListenerOpenActivity(findViewById(R.id.family),FamilyActivity.class);

}

public void setListenerOpenActivity (View view, final Class cActivity){
    view.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            startActivity(new Intent(MainActivity.this,cActivity));
        }
    });
}

}

@adda1
Copy link

adda1 commented Dec 26, 2019

When i write this code, the word setOnClickListener becimes red and says cannot resolve symbol. Why is this happening?

write the code inside of onCreate method.

@YASH2803
Copy link

YASH2803 commented May 9, 2020

When i write this code, the word setOnClickListener becimes red and says cannot resolve symbol. Why is this happening?

Same problem !!

@Ahmed-Salim-93
Copy link

Hi, my code is working just fine without problems.
The only issue is that in the video there is a back button in the title bar, but, is my program there isn't.
Does anyone know why is that happening and how to solve this problem?

@IQ-Hammurabi
Copy link

for any one faces problems :

  1. please make sure to paste the code inside onCreate method , otherwise the setOnClickListener will be RED, as below :

super.onCreate(savedInstanceState);

    // Set the content of the activity to use the activity_main.xml layout file
    setContentView(R.layout.activity_main);
    TextView numbers = (TextView) findViewById(R.id.numbers);
    numbers.setOnClickListener(new View.OnClickListener() {
        // The code in this method will be executed when the numbers View is clicked on.
        @Override
        public void onClick(View view) {
            Intent numbersIntent = new Intent(MainActivity.this, NumbersActivity.class);
            startActivity(numbersIntent);
        }
    });

2)please make sure that all these imports are in your MainActivity.java

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;

@noob-droid
Copy link

Please check if you've pasted this code within the onCreate method.

thank you for the solution. i am sort of curious though, why shall it be within the onCreate method?

@harshavardhan3199
Copy link

I think I'm the only one who things Katherine teaching is way better than the current one.

@Elghandour2020
Copy link

harshavardhan3199
Me too bro

@SultonN
Copy link

SultonN commented Aug 21, 2020

I want to share my version of the code:

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Set the content of the activity to use the activity_main.xml layout file
    setContentView(R.layout.activity_main);

    //Number Listener
    setListenerOpenActivity(findViewById(R.id.numbers),NumbersActivity.class);
    setListenerOpenActivity(findViewById(R.id.colors),ColorsActivity.class);
    setListenerOpenActivity(findViewById(R.id.phrases),PhrasesActivity.class);
    setListenerOpenActivity(findViewById(R.id.family),FamilyActivity.class);

}

public void setListenerOpenActivity (View view, final Class cActivity){
    view.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            startActivity(new Intent(MainActivity.this,cActivity));
        }
    });
}

}

@Goood

@vaibhavbhardwaj201
Copy link

Why do we pass (MainActviity,this, NumbersActivity,class) instead of (this, NumbersActivity.class)

Because we are in the Anonymous inner class. Class inside other class.

@Abhilashtyagi007
Copy link

put this code into the onCreate method

@yaz71
Copy link

yaz71 commented Sep 28, 2020

Question : do we have to copy past the code for all 4 categories ? or is it possible to just build one onclicklistener class and then use it on the 4 different textView objects ?

@yaz71
Copy link

yaz71 commented Sep 28, 2020

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Set the content of the activity to use the activity_main.xml layout file
    setContentView(R.layout.activity_main);
    TextView numbers= (TextView)findViewById(R.id.numbers);
    TextView phrases = (TextView)findViewById(R.id.phrases);
    TextView family = (TextView)findViewById(R.id.family);
    TextView colors = (TextView)findViewById(R.id.colors);

    numbers.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent Numb = new Intent(MainActivity.this, numbersActivity.class);
            startActivity(Numb);
        }
    });

    phrases.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent phrase = new Intent(MainActivity.this, phrasesActivity.class);
            startActivity(phrase);
        }
    });

    family.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent fam = new Intent(MainActivity.this, familyMembersActivity.class);
            startActivity(fam);
        }
    });

    colors.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent col = new Intent(MainActivity.this, colorsActivity.class);
            startActivity(col);
        }
    });
}

}

Here's my code, but I don't like the too much repetition :/ is there like an IF statement or a switch to use to implement this in less lines?

Copy link

ghost commented Oct 1, 2020

setOnClickListener

same with me

@Ahmostafaa
Copy link

Can anyone tell me what's wrong ?

error

@noxicus
Copy link

noxicus commented Jan 21, 2021

Can anyone tell me what's wrong ?

error

Check your brackets and semicolons

image

@nitish778191
Copy link

oopo
Can anyone explain this line of code please!

@bmramyabm
Copy link

Please check if you've pasted this code within the onCreate method.

Thanks

@Rishabh5752
Copy link

is anyone lost like me? :(

yes, i don't understand a single word of the video

@n0obs73r
Copy link

oopo
Can anyone explain this line of code please!

The first Parameter you are passing is the context of current activity because in case you want to press back after going to the next activity it'll act as a link and the next one is pretty self explanatory (it is passing the class you want to go to after clicking on the view).

@wdoodoo
Copy link

wdoodoo commented Jul 20, 2021

Hello, fellow coders.

I am sharing code based on my development environment as below.
I am using Android Studio 4.2.2, Build #AI-202.7660.26.42.7486908, built on June 24, 2021, Runtime version: 11.0.8+10-b944.6842174 amd64, VM: OpenJDK 64-Bit Server VM by N/A
openjdk version "11.0.10" 2021-01-19
OpenJDK Runtime Environment AdoptOpenJDK (build 11.0.10+9)
OpenJDK 64-Bit Server VM AdoptOpenJDK (build 11.0.10+9, mixed mode)

The MainActivity.java code is look like this and it works for me.
Hope this is helpful for someone out there. Happy coding!

``
package com.tutorial.android.miwok;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

     TextView numbers = findViewById(R.id.numbers);
     numbers.setOnClickListener(view -> {

        Intent numbersIntent = new Intent(this, NumbersActivity.class);
        startActivity(numbersIntent);
    });

    TextView family = findViewById(R.id.family);

    family.setOnClickListener(view -> {
        Intent familyIntent = new Intent(this, FamilyActivity.class);
        startActivity(familyIntent);
    });

    TextView colors = findViewById(R.id.colors);

    colors.setOnClickListener(view -> {

        Intent colorsIntent = new Intent(this, ColorsActivity.class);
        startActivity(colorsIntent);
    });

    TextView phrases = findViewById(R.id.phrases);

    phrases.setOnClickListener(view -> {

        Intent phrasesIntent = new Intent(this, PhrasesActivity.class);
        startActivity(phrasesIntent);
    });
}

}

@Harriskobia
Copy link

Note: If you don't want to create a Intent class, you can simply call the Intent constructor INSIDE the startActivity() method, like this:

TextView numbers = findViewById(R.id.numbers);

    numbers.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v){
            startActivity(new Intent(MainActivity.this, NumbersActivity.class));
        }
    });
}

This is actually nice

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment