开发者

onClick attribute in XML linking to method in Activity class

There are quite a few questions about this subject, but could not find any with the specific problem I have...

In my layout.xml, I use the android:onClick tag for a Button to call the right onClickListener. I get the error :

java.lang.IllegalStateException: Could not find a method handle_cancel(View) in the activity class com.matthieu.HelloWorldApplication for onClick handler on view class android.widget.Button with id 'button_cancel'

I have that method implemented in the Activity, but it is looking for it in the class that extends Application... I don't understand why. The View and all that is setup only in the Activity.

If anyone needs, here is the declaration of that method (in my activity, NOT in HelloWorldApplication):

public void handle_cancel(View v) {
    // do something useful here
}

Edit (from adamp request)... and probably answering my own question :

Here is part of the code where that layout is used...

public class AddVocabularyActivity extends Activity
{
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.top); // that layout contains an empty LinearLayout id/main_content
    }

    private some_other_function() {
        LinearLayout main_content = (LinearLayout) findViewById(R.id.main_content);
        main_content.removeAllViews();
        View.inflate(getApplicationContext(), R.layout.hello, main_content); // layout.hello is the one containing the button
    }

    // some other stuff
}开发者_高级运维

While copy/paste this code, I am guessing the problem is that I used getApplicationContext to inflate the View with that Button...


As mentioned in my edit, changing the getApplicationContext() with the Activity context fixes it...


The convention works like this: In the layout xml file, you give this attribute: android:onClick:"methodname"

Then, inside a class, you define a method like this:

public void methodname(View v){ //your method code }

Any other way of doing this is not documented. If you need parameters, just call another method inside that method.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜