Android/Java:如何从类引用到 MainActivity.java

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9674503/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 06:00:06  来源:igfitidea点击:

Android/Java: How to reference from a class to the MainActivity.java

javaandroidclass

提问by LiNalasNORDIC

Sorry for the question, probably it is answered within a few minutes. I'm new to Android App development and have been searching for an answer for about 2 hours, but I don't find a solution.

对不起,这个问题可能会在几分钟内得到回答。我是 Android 应用程序开发的新手,一直在寻找大约 2 个小时的答案,但我没有找到解决方案。

So, this is my problem: I created a MainActivity with a very simple layout, only one ToggleButton to start/stop some sound. I got it working with calling the MediaPlayer from within the MainActivity-Class. Now I want to put the MediaPlayer-Handling into a separate class, such that it can be called from a widget as well. When rising a Toast or calling a MediaPlayer-Method, I need to refer to the MainActivity, which was (in the MainActivity itself) "this". But I don't know how to refer to the instance of the MainActivity.

所以,这是我的问题:我创建了一个布局非常简单的 MainActivity,只有一个 ToggleButton 来启动/停止一些声音。我通过从 MainActivity-Class 中调用 MediaPlayer 来实现它。现在我想把 MediaPlayer-Handling 放到一个单独的类中,这样它也可以从一个小部件中调用。当启动 Toast 或调用 MediaPlayer-Method 时,我需要引用 MainActivity,它是(在 MainActivity 本身中)“this”。但是我不知道如何引用 MainActivity 的实例。

The code is as follows:

代码如下:

package com.heavyloadreverse;

//import java.io.IOException;

import android.app.Activity;
//import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
//import android.widget.Toast;
import android.widget.ToggleButton;

public class MainActivity extends Activity {

    //private MediaPlayer mp;
    private Sound snd;
    private ToggleButton btn;   

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        btn = (ToggleButton) findViewById(R.id.btn_OnOff);
        snd = new Sound();
        snd.mp_create(MainActivity.this);
    }

    public void onToggleClicked(View v) {       
        // Perform action on clicks
        if (((ToggleButton) v).isChecked()) {            
            snd.mp_start();
        } else {            
            snd.mp_stop();
        }
    }

    /*********************************************************************************
    public void mp_create() {
        mp = MediaPlayer.create(this, R.raw.truckreverse);
    }

    public void mp_start () {
        Toast.makeText(this, R.string.start, Toast.LENGTH_SHORT).show();
        // start the sound  
        mp.setLooping(true);
        mp.start();
    }

    public void mp_stop () {
        Toast.makeText(this, R.string.stop, Toast.LENGTH_SHORT).show();
        // stop the sound
        mp.stop();
        try {
            mp.prepare();
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public void mp_init() {
        btn.setChecked(false); 
    }
    **********************************************************************************/

    public void btn_init() {
        btn.setChecked(false); 
    }   

    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    public void onRestart() {
        super.onRestart();      
        btn_init();     
    }

    @Override
    public void onResume() {
        super.onResume();
        btn_init();
    }

    @Override
    public void onPause() {
        super.onPause();
        snd.mp_stop();
    }

    @Override
    public void onStop() {
        super.onStop();
        snd.mp_stop();
    }

    @Override
    public void onDestroy() {
        super.onDestroy(); 
        snd.mp_stop();
    }

    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
        super.onSaveInstanceState(savedInstanceState);      
    }

}

The class for the MediaPlayer-Handling:

MediaPlayer-Handling 的类:

package com.heavyloadreverse;

import java.io.IOException;

import android.app.Application;
import android.media.MediaPlayer;
import android.widget.Toast;
import com.heavyloadreverse.R;

public class Sound extends Application {

    private MediaPlayer mp; 

    public void mp_create (MainActivity main) {
        Toast.makeText(main.this, "test", Toast.LENGTH_SHORT).show();
        mp = new MediaPlayer();
        try {
            mp = MediaPlayer.create(this, R.raw.truckreverse); 
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (RuntimeException e) {
            e.printStackTrace();
        }       
    }

    public void mp_start () {
        Toast.makeText(MainActivity.this, R.string.start, Toast.LENGTH_SHORT).show();
        // start the sound  
        try {
            mp.setLooping(true);
            mp.start();
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (RuntimeException e) {
            e.printStackTrace();
        }       
    }

    public void mp_stop () {
        //Toast.makeText(this, R.string.stop, Toast.LENGTH_SHORT).show();       
        try {
            // stop the sound
            mp.stop();
            mp.prepare();
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (RuntimeException e) {
            e.printStackTrace();
        }
    }

}

Toast.makeText(this, "test", Toast.LENGTH_SHORT).show();

Toast.makeText(this, "test", Toast.LENGTH_SHORT).show();

--> raises a runtime-error when executing:

--> 执行时引发运行时错误:

--> 03-12 20:23:18.412: E/AndroidRuntime(862): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.heavyloadreverse/com.heavyloadreverse.MainActivity}: java.lang.NullPointerException

--> 03-12 20:23:18.412: E/AndroidRuntime(862): java.lang.RuntimeException: 无法启动活动组件信息{com.heavyloadreverse/com.heavyloadreverse.MainActivity}: java.lang.NullPointerException

Toast.makeText(main.this, "test", Toast.LENGTH_SHORT).show();

Toast.makeText(main.this, "test", Toast.LENGTH_SHORT).show();

--> error in code:

--> 代码错误:

--> *Multiple markers at this line - main cannot be resolved to a type - Line breakpoint:Sound [line: 15] - mp_create(MainActivity)*

--> *此行有多个标记 - main 无法解析为类型 - Line breakpoint:Sound [line: 15] - mp_create(MainActivity)*

Toast.makeText(MainActivity.this, "test", Toast.LENGTH_SHORT).show();

Toast.makeText(MainActivity.this, "test", Toast.LENGTH_SHORT).show();

--> error in code:

--> 代码错误:

--> No enclosing instance of the type MainActivity is accessible in scope

-->在范围内没有可访问类型 MainActivity 的封闭实例

What do I have to do in order to make the Toast- and MediaPlayer-Calls in "Sound.java" working?

我该怎么做才能使“Sound.java”中的 Toast- 和 MediaPlayer-Calls 工作?

Thanks a lot in advance.

非常感谢。

Sven

斯文

回答by kosa

For Toast this is what you need to do:

对于 Toast,这是您需要做的:

Toast toast=Toast.makeText(this, "Hello toast", 2000);

     toast.show();

Check this tutorial tutorial if it helps.

如果有帮助,请查看本教程

回答by LuizAurio

Not sure if this work, only an idea.

不确定这是否有效,只是一个想法。

Firs of all extend your Sound class from your MainActivity

首先从 MainActivity 扩展 Sound 类

public class Sound extends MainActivity {

second, this is the code I use for Toast to work:

其次,这是我用于 Toast 工作的代码:

Toast.makeText(MainActivity.this,"Your Text Here",Toast.LENGTH_LONG).show();

回答by Axxiss

Option 1Add 'Context' as a parameter on 'Sound'

选项 1添加“上下文”作为“声音”的参数

public class Sound{
    private Context mContext;
    Sound(Context context){
        mContext = context;
    }

    ...
    Toast.makeText(mContext, text, length).show();
    ...
}

When you create Soundfrom activity you will do it like new Sound(this);

当您Sound从活动创建时,您会这样做new Sound(this);

Option 2

选项 2

Define an interface in Sound to provide callbacks

在 Sound 中定义一个接口来提供回调

public class Sound {
    interface OnSoundListener{
        public void onSoundStarted();
        public void onSoundStopped();
    }
}

And your main activity will look like

你的主要活动看起来像

public class MainActivity implements Sound.OnSoundListener{
    @Override
    public void onSoundStarted(){
        //your toast here
    }
}

Personally I prefer the second one, that way you can separate logic from UI.

我个人更喜欢第二个,这样你就可以将逻辑与 UI 分开。