简体   繁体   English

在没有Activity的另一个类文件中使用Toast扩展了Android

[英]Using Toast in another class file without Activity extends Android

I've 2 files: Core (extends Activity) and DwCore. 我有2个文件:Core(扩展Activity)和DwCore。 I'm using AsyncTask in a Core subclass and I want to use Toast in DwCore subclass but I can't get properly the Core Context. 我在Core子类中使用AsyncTask,并且想在DwCore子类中使用Toast,但是我无法正确获取Core Context。

Core 核心

class DwFiles extends AsyncTask<Void, Void, Long> {
    protected Long doInBackground(Void... parms) {
        long totalSize = 0;
        dwCore.mainCounter(Core.this);
        return totalSize;
    }
}

DwCore subclass DwCore子类

public void mainCounter(Context c){
    Integer count = 0;
    for(int i=0;i<count;i++){
        Toast.makeText(c, count.toString(), Toast.LENGTH_SHORT).show();
    }
}

You can't do anything that affects the UI from worker threads - that includes showing toasts. 您不能做任何会影响工作线程中的UI的事情-包括显示敬酒。

class DwFiles extends AsyncTask<Void, Void, Long> {
protected Long doInBackground(Void... parms) {
    long totalSize = 0;
     publishProgress(check_point);
    return totalSize;
}
}

protected void onProgressUpdate(Integer integers) {
   dwCore.mainCounter(Core.this);
}
public void mainCounter(Context c){
Integer count = 0;
     for(int i=0;i<count;i++){
         Toast.makeText(getActivity(), count.toString(), Toast.LENGTH_SHORT).show();
    }
}

You can use getActivity() function or this.getActivity(). 您可以使用getActivity()函数或this.getActivity()。
getActivity() can be used in a Fragment for getting the parent Activity of the Fragment (basically the Activity that displayed the Fragment). 可以在Fragment中使用getActivity()来获取Fragment的父Activity(基本上是显示Fragment的Activity)。

can't be done as doInBackGround runs on a background thread which cant access the ui thread. 由于doInBackGround在无法访问ui线程的后台线程上运行,因此无法完成。 What you can do is ,Create an Custom interface implement it on your activity then push the ui related update from the onProgressUpdate(). 您可以做的是,创建一个Custom接口,在您的活动中实现该接口,然后从onProgressUpdate()推送与ui相关的更新。

    Interface ProgUpdate{
void uiUpdate(int update)
}

BackGround theread :
ProgUpdate listener;

onProgressUpdate(Int i){
listener.uiUpdate(i)
}

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

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