How to use Toast when I cant use “this” as context

橙三吉。 提交于 2019-12-03 15:44:39

问题


I have a location listener activity and I want to make toast notifications. But it will not let me pass this as the context. How should I make toast work?


回答1:


If the toast is located inside your activity class, you could use YourActiviy.this where YourActivity is the class name. If it's outside your class, you'll need to get your activity context (pass it in the constructor etc).




回答2:


If you are in the inner Class then try this also

getApplicationContext()




回答3:


You can use NameOfYourActivity.this

For example:

public class MyActivity extends Activity {

 ...
     Toast.makeText(MyActivity.this, text, duration).show();



回答4:


Field variable: Context context;

inside OnCreate: context = this;

Xamarin / C# Syntax: Toast.MakeText(context, "your message", ToastLength.Long).Show();

Android / Java syntax: Toast.makeText(context, "your message", Toast.LENGTH_LONG).show();




回答5:


For example, if you have a listener with a method called "onComplete" inside it, this code should work.

public void onComplete(String response, Object state) {
        final String response_complete = response;
        MyActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(MyActivity.this, text, duration).show();
            }
        });
    }

That should do it.




回答6:


It sounds like you are in an inner class in the Activity. If thats the case, try ActivityName.this.




回答7:


instead try getApplicationContext()

 Toast tea = Toast.makeText(getApplicationContext(), "Send", Toast.LENGTH_LONG);
 tea.show();


来源:https://stackoverflow.com/questions/5641103/how-to-use-toast-when-i-cant-use-this-as-context

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!