开发者

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

开发者 https://www.devze.com 2023-03-17 04:20 出处:网络
I have defined a model class: public class MyObject { ... } In my activity, I get this object from SERVICE layer. Everything works fine at th开发者_如何学编程is point, my only question is, in Activ

I have defined a model class:

public class MyObject {
    ...
}

In my activity, I get this object from SERVICE layer. Everything works fine at th开发者_如何学编程is point, my only question is, in Activity, if I set setOnClickListener to a TextView, how can I access myObject? What I mean is showing in the following code:

//my custom object
MyObject obj = SERVICE.getObject();

TextView tx = new TextView(this);
tx.setText("Click me");
tx.setOnClickListener(
     new OnClickListener(){

             @Override
             public void onClick(View v){

                //how to access obj here? 
             }
      }
);

In the above code, I can not access obj inside onClick(View v) function, how to get rid of it to access obj inside onClick(View v) ?


Mark MyObject obj as final.

final MyObject obj = SERVICE.getObject();

TextView tx = new TextView(this);
tx.setText("Click me");
tx.setOnClickListener(
     new OnClickListener(){

             @Override
             public void onClick(View v){
                obj.doStuff(); //this should work now...
             }
      }
);


If you have an ID, you can set that ID on the tag field and retrieve it in the onclick:

tx.setTag(obj.getId());
tx.setOnClickListener(
    new OnClickListener(){
        @Override
        public void onClick(View v){
            Long id = v.getTag();
        }
    }
);

You can store an arbitrary object, so you could potentially store the whole object there.


Set your object as final and you can get access to it.


There is a simpler method:

class testClass
{
    testClass obj;
    public testClass() {
        obj=this;
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        TextView tx = new TextView(this);
        tx.setText("Click me");
        tx.setOnClickListener(
            new OnClickListener() {
                @Override
                public void onClick(View v) {
                    obj.doStuff(); //this should work now...
                }
            }
        );
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消