开发者

how to show toast in Runnable class on Java, Android? [closed]

开发者 https://www.devze.com 2023-04-06 09:53 出处:网络
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical andcannot be reasonably answered in its current form. For help clari
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. 开发者_StackOverflow中文版 Closed 11 years ago.

I have a class implements Runnable interface, and I need show Toast from this class. How can I do that?


You can make use of handlers to display a Toast. Because few things in Android must be done from UI thread only. Try this,

Do this in your onCreate(),

      handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            progressDialog.cancel();
            if (msg.what == 0) {
            Toast.makeText(Catering.this,"Hi toast",Toast.LENGTH_LONG).show();

            }
     }};

And now your thread,

    final Thread Fetcher = new Thread(new Runnable() {

        public void run() {
                    handler.sendEmptyMessage(0);

             });
    Fetcher.start();


The issue isn't whether or not it implements Runnable. The issue is that it has to be run by the main display thread, and will need access to the Activity's context. If you paste your code, we can help you fix it.


I think you are getting error because you are creating and showing Toast from a NON-GUI thread. You can only write to the display from the GUI thread. Post your code for us to help you further.


I think you want to do as like:

current class:

take a contex's object and pass contex.this to implemented class's constructor.

in that constructor you should write:

this.context1 = context;

at the toast showing you should pass context1.

i think this will help you.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号