gpt4 book ai didi

android - 在android中,如果我在线程中运行网络请求但不想在响应返回之前刷新UI怎么办?

转载 作者:行者123 更新时间:2023-11-30 05:04:00 25 4
gpt4 key购买 nike

就像我需要检查用户名是否已经存在于数据库中,并且在响应到达之前程序不会继续。

最佳答案

看来您需要 asynctask,这是一个如何使用它的示例..

    public class YourFragment extends Fragment implements YourAsyncTask.YourInterface {


public YourFragment() {
// Required empty public constructor
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

View view = inflater.inflate(R.layout.fragment_your, container, false);



//do your initial things
.
.
.

YourAsyncTask yourAsyncTask = new YourAsyncTask(this);
yourAsyncTask.execute();

return view;
}

@Override
public void onJobFinishListener(YourDataType yourData) {
//when this method is trigered by your asynctask
//it means that you are in ui thread and update your ui component

//TODO: update ui component with your data
}
}

这是异步任务;

public class YourAsyncTask extends AsyncTask {

private YourInterface yourInterfaceListener;

private YourDataType yourData; //this data should be calculated in doInBackground method and send via interface

public YourAsyncTask(YourInterface yourInterfaceListener) {
this.yourInterfaceListener = yourInterfaceListener;
}

@Override
protected Object doInBackground(Object[] objects) {
//do your all background tasks here
.
.
.
yourData = do something here to fill your data..

return null;
}

@Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
yourInterfaceListener.onJobFinishListener(yourData);
}

public interface YourInterface{
void onJobFinishListener(YourDataType yourData);
}
}

关于android - 在android中,如果我在线程中运行网络请求但不想在响应返回之前刷新UI怎么办?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54880902/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com