【问题标题】:Android Calling Method in Activity ClassActivity类中的Android调用方法
【发布时间】:2015-02-27 18:09:27
【问题描述】:

我有一个名为 Second.java 的 java 类,它有一个名为 toast_method() 的方法。 我的问题是,如何从 Second.java 中调用 toast_method(),然后在应用中显示 toast 消息?

我尝试了以下代码,但它不起作用

Second.java

package com.example.callmethod;

import android.content.Context;
import android.widget.Toast;

public class Second {

        Context context;

        public Second(Context context) {
            this.context = context;
        }

        public void toast_method() {
            Toast.makeText(context, "Hello", Toast.LENGTH_SHORT).show();

        }

}

MainActivity.java

package com.example.callmethod;

import android.app.Activity;
import android.os.Bundle;

public class MainActivity extends Activity {

    private Second myotherclass;

            @Override
            public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_main);

                // Calling the method from Second Class
                myotherclass.toast_method();

            }

}

谢谢

【问题讨论】:

    标签: java android class methods


    【解决方案1】:

    简单的一个^^

    您必须扩展 Activity 才能在 Activity 中使用上下文

    public class operation extends Activity {
    
        // normal toast
        //you can change length
        public static void toast(String toastText, Context contex) {
            Toast.makeText(contex, toastText, Toast.LENGTH_LONG).show();
        }
        // Empty Toast for Testing
        public static void emptyToast(Context contex) {
            Toast.makeText(contex, R.string.EmptyText, Toast.LENGTH_LONG).show();
        }
    
    }
    

    现在...在您的活动中仅调用函数

    operation.toast("Your Text",currentClass.this);
    

    例子:

    public class currentClass extends Activity {
    
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.mylayout);
    
             operation.toast("Hello",currentClass.this);
        }
    }
    

    【讨论】:

      【解决方案2】:

      你快到了!只缺少第二类的重要实例化:

             @Override
              public void onCreate(Bundle savedInstanceState) {
                  super.onCreate(savedInstanceState);
                  setContentView(R.layout.activity_main);
      
                  // Calling the method from Second Class
                  myotherclass = new Second(this); // <----- this
                  myotherclass.toast_method();
      
      
              }
      

      【讨论】:

      • 谢谢哥们 :) 有一个伟大的一年
      【解决方案3】:

      在 onCreate 中这样做

      Second second =new Second(this);
      second.toast_method();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-04-10
        相关资源
        最近更新 更多