Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

android

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?

like image 694
Ted Avatar asked Jan 16 '10 03:01

Ted


People also ask

What is the only method of the view OnClickListener interface?

In Android, the OnClickListener() interface has an onClick(View v) method that is called when the view (component) is clicked. The code for a component's functionality is written inside this method, and the listener is set using the setOnClickListener() method.

How do I use OnClickListener?

If you have more than one button click event, you can use switch case to identify which button is clicked. Link the button from the XML by calling findViewById() method and set the onClick listener by using setOnClickListener() method. setOnClickListener takes an OnClickListener object as the parameter.

Why my setOnClickListener is not working?

You need to put the setOnClickListener in one of the activity callbacks. In your onCreate() method, move the button there and then setOnClickListener() . Show activity on this post.

What is new view OnClickListener?

The onClickListener is constructed as: new View.OnClickListener() { public void onClick(View v) { } } That onClick method is used by the listener to handle the event (in this case, a button press).


1 Answers

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.

like image 162
Lance Nanek Avatar answered Oct 26 '22 20:10

Lance Nanek