简体   繁体   English

从Java类调用活动方法

[英]Calling activity method from java class

Im asking to see if anyone could help me with my problem which is that I have a custom dialog box in a java class. 我问我是否有人可以帮助我解决我的问题,即我在java类中有一个自定义对话框。 This custom dialog box has a button which when pressed will call a method from my activity class. 这个自定义对话框有一个按钮,当按下该按钮时,它将从我的活动类中调用一个方法。 When I run the code nothing happens, it seems that the method is never being called and also no errors are given, the reason that im trying it this way is because the java class is being used for overlayitems. 当我运行代码时,什么也没发生,看来该方法从未被调用过,也没有给出错误,我这样尝试的原因是因为java类被用于overlayitems。 Below is a snippit of the code that I have, cheers to anyone who has insight on the problem 以下是我所拥有的代码的摘要,向对这个问题有深刻见解的任何人欢呼

Java Class for overlayitem 覆盖项目的Java类

    public boolean onTap(int index) {
    OverlayItem item = mapOverlays.get(index);
    Dialog dialog = new Dialog(context);

    dialog.setContentView(R.layout.dialog);
    dialog.setTitle(item.getTitle());

    TextView text = (TextView) dialog.findViewById(R.id.text);
    text.setText(item.getSnippet());
    Button CallButton = (Button) dialog.findViewById(R.id.CallButton);
    CallButton.setOnClickListener(new View.OnClickListener()
    {
        public void onClick(View v) 
        {
            try {
                TheActivityClass.showMessage();
            } catch (Exception e) {
                // TODO Auto-generated catch block

            }
        }
    }
    );
    dialog.show();
    return true;

}

Activity Class 活动课

public void showMessage(){



        Context context = getApplicationContext();
        CharSequence text = "I have just been pressed";
        int duration = Toast.LENGTH_SHORT;

        Toast toast = Toast.makeText(context, text, duration);
        toast.show();


    }

You have an encapsulation problem... The activity class is not on the top of the current stack and the showMessage() method is not static. 您有封装问题...活动类不在当前堆栈的顶部,并且showMessage()方法不是静态的。

You should be controlling the application logic from inside the Activity class not the Java overlay class (follow the MVVM logic ie MVC where the activity is your controller). 您应该从Activity类而不是Java overlay类内部控制应用程序逻辑(遵循MVVM逻辑,即MVC,其中Activity是您的控制器)。 The best option would be to encapsulate the dialog/overlay object in the Activity and set the logic within the Activity class (create appropriate methods in the overlay class to do this) or to just make your overlay and inner class of the Activity. 最好的选择是将对话框/覆盖对象封装在Activity中,并在Activity类中设置逻辑(在overlay类中创建适当的方法以执行此操作),或者仅使Activity的覆盖层和内部类成为对象。 This will allow you do to what you are trying to do. 这将使您能够做自己想做的事情。

Hope that helps. 希望能有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM