vxh.viet
4/19/2016 - 10:44 AM

How to reference an object that call OnClickListener from inside the listener?

How to reference an object that call OnClickListener from inside the listener?

Source: StackOverflow

Question: How to access the object that call setOnClickListener() from inside the listener?

Answer:

In your onClick(View v) you can cast it to your object:

Button button = (Button) findViewById(R.id.button_id);
button.setOnClickListener(new View.OnClickListener() {
   public void onClick(View v) {
        Button clickedButton = (Button)v;
        // do stuff with it here.
   }
});

Source: StackOverflow

Question: How to access outer class from inside the OnClickListener

Answer: 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.

findViewById(R.id.Button01).setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                List<ActivityInfo> activities = this.getPackageManager().queryIntentActivities(mainApps, 0);
            }
        });

Source: StackOverflow

Question: How to access my object inside onClick(View v) function?

Answer:

Mark MyObject obj as final.

final MyObject obj = SERVICE.getObject();

TextView tx = new TextView(this);
tx.setOnClickListener(new OnClickListener(){
   @Override
   public void onClick(View v){
      obj.doStuff(); //this should work now...
   }
  }
);

Source: StackOverflow

Question: How to access loop index inside setOnClickListener?

Answer:

Declare a final int index = i inside the loop like this:

ViewGroup vg = ((ViewGroup) findViewById(R.id.filter_panel));

        for(int i = 0; i < vg.getChildCount(); i++){
            final int index = i;

            vg.getChildAt(i).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mMyFilterView.setLUTBitmap(MyValues.filterID[index]);
                }
            });
        }