开发者

Passing information back from EventListener to Activity

开发者 https://www.devze.com 2023-01-24 07:54 出处:网络
I\'m new to Android, and event driven code in general. Rather than embed loads of anonymous event listener classes in my Activity to handle onClick events etc, I defined separate classes to keep the c

I'm new to Android, and event driven code in general. Rather than embed loads of anonymous event listener classes in my Activity to handle onClick events etc, I defined separate classes to keep the code clean. Then I use them e.g. like this

myButton.setOnClickListener(new MyEventListener());

So, when 'myButton' gets clicked, MyEventListener's onClick metho开发者_JAVA技巧d does some stuff.

I wanted to know the best practice for

a) accessing things in my Activity from the event listener. For example to change the text of a label. The onClick event takes a View in, but this is the view for the button that's been clicked, so if the label is NOT a child of my button, I can't use findViewById to get a handle to it. I've modified the constructor to pass in a reference to the label, so that the event has a handle to it but not sure if this is the most elegant way of doing it.

b) Passing information back e.g. when my event fires, I might want to disable some EditText fields. I'm thinking the proper way to do this is probably to dispatch another event from my event listener, that the Activity listens for, and when it sees the event, disables the fields in question. Is that the way to do it in Android?

Hope someone can help, really appreciate it.

Thanks


An alternative to using explicit event listeners, anonymous or not, is to use the onClick attribute in xml to directly dispatch to a method as in the following example:

Layout xml file:

 <Button android:onClick="buttonClickedCallback" />

Now simple define a method on your activity:

class CustomActivity extends Activity {
    public void buttonClickedCallback(View clickedButton) {
        // do stuff
    }
}

This is available since Android 1.6 as described in UI framework changes in Android 1.6.

0

精彩评论

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