Inside OnClickListener I cannot access a lot of things - how to approach?

Inside an OnClickListener I cannot access most variables "outside" of the scope, like this:

findViewById(R.id.Button01).setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                Intent mainApps = new Intent(Intent.ACTION_MAIN);
                mainApps.addCategory(Intent.CATEGORY_LAUNCHER);
                List<ActivityInfo> activities = this.getPackageManager().queryIntentActivities(mainApps, 0);
                /*
                Intent intent = new Intent("com.sygic.drive/com.sygic/drive/.SygicDriveActivity");
                startActivity(intent);*/
            }

        });

in this example I need to get the PacketManager, and I cannot get it since I do not have the Context available inside the OnClickListener.

I could make a static reference outside, and use it inside, but is that correct? Seems odd to have to do that all the time?


Asked by: Julian420 | Posted: 20-01-2022






Answer 1

Replace this in your code with MyActivity.this where MyActivity is the class name of your Activity subclass.

Explanation: You are creating an anonymous inner class when you use this part of your code:
new OnClickListener() {
Anonymous inner classes have a reference to the instance of the class they are created in. It looks like you are creating it inside an Activity subclass because findViewById is an Activity method. Activity's are a Context, so all you need to do is use the reference to it that you have automatically.

Answered by: Kevin325 | Posted: 21-02-2022



Answer 2

You could also implement the OnClickListener interface in your class and avoid the need for an anonymous inner class. Then you would set the on click listener like this:

findViewById(R.id.Button01).setOnClickListener(this);

If you have multiple buttons using one listener, you can use a switch statement with view.getId() (which corresponds to the view's id in R.id) to distinguish between them.

Answered by: Blake433 | Posted: 21-02-2022



Answer 3

There are a few things you can do, you can create an inner class that implements the onClickListener and pass the necessary arguments into the constructor of the class. I still don't find that the cleanest approach. I usually just create another method to perform my action. So in the onClick(View v) I would do something like this.

onClick(View v){doMyAction(myParams)}

private void doMyAction(Object params){//do stuff}

And just pass the needed params from the listener method to the method outside the listener.

Answered by: Melissa142 | Posted: 21-02-2022



Answer 4

Change the Intent constructor in use to Intent(context, classname) and use getApplicationContext() in your innerclass. Solved my problem anyway.

Answered by: Kelvin120 | Posted: 21-02-2022



Similar questions

android - onClickListener on a LinearLayout

Got a little problem with a functionality I'd like to implement. I've got a LinearLayout, containing 2 TextViews. I'd want to set a onClickListener on it, so that it would behave just like an item in a ListView. I've tried some possible implementation of this, and got it working using the xml attribute android:onClick of the LinearLayout...


java - Android: When I set an OnClickListener for a ListView

lv.setOnClickListener(new OnClickListener(){ public void onClick(View v){ } }); Does v refer to the ListView lv or the specific item selected in the list?


EditText onClickListener in Android

I want an EditText which creates a DatePicker when is pressed. So I write the following code: mEditInit = (EditText) findViewById(R.id.date_init); mEditInit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showDialog(DATEINIT_DIALOG); } }); But when I press the EditText the action is the typical: a curs...


android - MapActivity launching from OnClickListener

Just started working with android and ran into a small problem. I am have a TabActivity that is loading 3 other Activity classes. This works great. I then have a button on the other Activity classes that I would like to launch a MapActivity. When I do that I keep getting a Force Close. I googled but I cannot figure out if it is the manifest file or something else. The idea is the tabs are showing location informat...


android - OnClickListener error: Source not found

I'm brand new to Android development and right now I am building a simple calculator for healthcare workers. My program implements the OnClickListener class, but every time I click on the button to initiate the calculation, I get an error saying the "Source is not Found". Here is the code: public class KidneyeGFR extends Activity implements OnClickListener { TextView EditAge; TextView EditSerum; Tex...


android - Play sound without onClickListener

How can I play a sound in an activity without requiring the press of a button? I already know how to play the sound, but need to bypass the onClickListener. Thanks for any advice.


events - Android OnClickListener - identify a button

I have the activity: public class Mtest extends Activity { Button b1; Button b2; public void onCreate(Bundle savedInstanceState) { ... b1 = (Button) findViewById(R.id.b1); b2 = (Button) findViewById(R.id.b2); b1.setOnClickListener(myhandler); b2.setOnClickListener(myhandler); ... } View.OnClickListener myhandler = new View.OnClickListener() { public void onClick(View v)...


android - OnClickListener and OnTouchListener

I have an 2 adapters extending BaseAdapater. The first Adapter (let's call it imageAdapter) loads an image base on an ID, the second adapter (pageAdapter) builds grids of images from the first adapter. I set the second adapter to a gallery. The idea is that I can sort have pages in an album where there are multiple pictures on each album. Now I want to the imageViews to fire off clicks, so I set an onClickListener...


java - OnClickListener not firing from Parent class

A Follow up to this question: Group of Views (controls) on multiple screens I have created a parent class and a child class that inherits from it. When I set the OnClickListener in the child class, the event fires when the button is clicked. When I move the set OnClickListener to the parent class, the event doesn...


onclicklistener - onclick listener in android

I used two image button for Next and Back and i used onclick event for those button i want to which image button fire on onclick and run particular function for next or back in onclick event how will i get which image button fire or onclick event at runtime






Still can't find your answer? Check out these communities...



Android Google Support | Android Community | Android Community (Facebook) | Dev.io Android



top