我试图从片段内的AsyncTask接收数据。我知道通过活动实现这一目标但是片段有困难。
GetResult类
public interface GetResult {
void getData(ArrayList<String> result);
}
myFrag类
public class myFrag extends Fragment implements GetResult{
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.myFrag_layout, container, false);
Button myBtn = (Button) view.findViewById(R.id.Button1);
myBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
myAsync obj = new myAsync();
obj.setListener(getActivity());
}
});
}
}
myAsync类
public class myAsync extends AsyncTask<Void, Void, String>{
GetResult interfaceObj = null;
public void setListener( GetResult interfaceObj ) {
this.interfaceObj = interfaceObj;
}
}
我遇到了obj.setListener(getActivity)的问题。它说myAsync类型中的方法setListener(GetResult)不适用于参数(FragmentActivity)。在此先感谢大家。
答案 0 :(得分:0)
我没有想出wt问题,但还有另一种方法可以做到这一点。我将在这里分享。
第1个接口类GetResult.class是相同的
片段类myFrag.class的第二次更改
public class myFrag extends Fragment{
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.myFrag_layout, container, false);
Button myBtn = (Button) view.findViewById(R.id.Button1);
myBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
getLoc obj = new getLoc(getActivity(), new GetResultInterface() {
@Override
public void processFinish(ArrayList<String> result) {
// U can get the result here
}
obj.execute(url);
});
}
}
在AsyncTask中的第三个myAsync.class
public class myAsync extends AsyncTask<Void, Void, String>{
Context context;
GetResult interfaceObj = null;
public myAsync(Context context, GetResultInterface interfaceObj) {
this.context = context;
this.interfaceObj = interfaceObj;
}
@Override
protected void onPostExecute(ArrayList<String> result) {
super.onPostExecute(result);
interfaceObj.processFinish(result);
}
}