简体   繁体   English

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

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

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 App开发的新手,已经搜寻了大约2个小时的答案,但是找不到解决方案。

So, this is my problem: I created a MainActivity with a very simple layout, only one ToggleButton to start/stop some sound. 因此,这就是我的问题:我创建了一个MainActivity,布局非常简单,只有一个ToggleButton可以启动/停止一些声音。 I got it working with calling the MediaPlayer from within the MainActivity-Class. 我通过在MainActivity-Class中调用MediaPlayer使其工作。 Now I want to put the MediaPlayer-Handling into a separate class, such that it can be called from a widget as well. 现在,我想将MediaPlayer-Handling放入一个单独的类中,以便也可以从小部件中调用它。 When rising a Toast or calling a MediaPlayer-Method, I need to refer to the MainActivity, which was (in the MainActivity itself) "this". 当举起Toast或调用MediaPlayer-Method时,我需要引用MainActivity,它在MainActivity本身中是“ this”。 But I don't know how to refer to the instance of the MainActivity. 但是我不知道如何引用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:无法启动活动ComponentInfo {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调用正常工作,我该怎么做?

Thanks a lot in advance. 非常感谢。

Sven 斯文

Option 1 Add '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 Sound from activity you will do it like new Sound(this); 当您通过活动创建Sound ,您将像new Sound(this);一样执行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分开。

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();

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. 如果有帮助,请查看本教程

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

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