当前位置: 首页 > 知识库问答 >
问题:

getContext()、getApplicationContext()、getBaseContext在Android中不起作用

宗政燕七
2023-03-14

我想显示toast消息,但是toast.Maketext((getContext(),“message”,toat.length_long.show()))中的getContext()出现错误

public class myClass extends AsyncTask<String, String, String> {

public myClass(double a, double b,Context context ) {
    this.a = a;
    this.b=b;
    this.context = context;
}


protected String doInBackground(String... params) {
        return null;
    }

    protected void onPostExecute(String result) {
               Toast.makeText((getApplicationContext(), "Message", Toast.LENGTH_LONG).show();

    }
}
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends AppCompatActivity {

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

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                double age = 16;
                double number = 33;
                Object = new myClass(age,number,this);
            }
        });
    }


}
    import android.content.Context;
    import android.os.AsyncTask;
    import android.widget.Toast;

    public class myClass extends AsyncTask<String, String, String> {

        Context context;
        double a;
        double b;
        public myClass(double a, double b,Context context ) {
            this.a = a;
            this.b=b;
            this.context = context;
        }


        protected String doInBackground(String... params) {
            return null;
        }

        protected void onPostExecute(String result) {
            Toast.makeText((context), "Message", Toast.LENGTH_LONG).show();
        }
    }

共有1个答案

霍襦宗
2023-03-14

当您使用时,这个引用了封闭类。在您的示例中,这是view.onClickListener。但是你需要传递你的活动的上下文。

所以你需要这样称呼它,

Object = new myClass(age,number, MainActivity.this);
 类似资料: