![](/img/trans.png)
[英]MainActivity to Fragment and from that Fragment back to MainActivity
[英]Notify a Fragment of onPostExecute from MainActivity
在Android中,我很难弄清楚AsyncTask完成后如何通知正在监听的Fragment。 似乎没有Java常用的东西,例如PropertyChangeLIstener
。 因此,在onPostExecute
,我想触发一个事件并让OtherFragment
看到。
我该怎么做呢?
public class MainActivity extends FragmentActivity {
<stuff>
private class ConsumeWebService extends AsyncTask
<String, // type of the parameters sent to the task upon execution - doInBackground()
Integer, // type of the progress units published during the background computation -onProgressUpdate()
String> {
public ConsumeWebService(SomeKindOfListener listener){
this.myListener = listener;
}
protected String doInBackground(String... urls) {
< get JSON data from RESTful service>
< create and populate SQLite db wit JSON data>
return jsonData;
}
@Override
protected void onPostExecute(String result) {
try {
<fire some kind of event>
}
catch (Exception e) {
}
}
}
}
public class OtherFragment extends Fragment implements SomeKindOfListener {
@Override
public void someKindOfChange(SomeKindOfChangeEvent arg0) {
< do the stuff we want to do>
}
}
public interface SomeKindOfListener {
void onPostExecuteDone();
}
使用FragmentManager:
SomeKindOfListener listener = (SomeKindOfListener )
getFragmentManager().findFragmentById(R.id.myFragment);
new ConsumeWebService(listener);
和:
@Override
protected void onPostExecute(String result) {
try {
this.myListener.someKindOfChange();
}
catch (Exception e) {
}
}
我会做这样的事情:
1-具有界面
public interface OnXListener {
void onX(Object data);
}
2-有片段实现它
public class MyFragment extends Fragment implements OnXListener{
public void onX(Object data) {
doSomething(data);
}
public void doSomething(data) {
/do the real thing
}
}
3-完成异步任务后在活动中调用此方法
public class MyActivity extends Activity {
Fragment mMyFragment fragment;
//stuff, initializate fragment, show fragment, etc.
private class MyAsyncTask extends AsyncTask {
//stuff
@override
protected void onPostExecute(Object result) {
((OnXListener) MyActivity.this.mMyFragment).onX(result);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.