我想调用一个位于片段中的内部asynctask。我想从使用asynctask托管此片段的父片段调用asynctask。该父片段包括具有多个片段的viewpager。 我知道我必须使用界面并尝试了一些东西,但它不起作用。
接口
public interface OnFragmentButtonListener {
void onMyButtonClicked();
}
FRAGMENT
public class FragmentQueue extends SherlockFragment implements OnFragmentButtonListener
{
...
@Override
public void onMyButtonClicked() {
new LoadQueueTask().execute();
}
}
PARENT FRAGMENT
public class ParentFragment extends SherlockFragment{
...
refresh.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
((OnFragmentButtonListener)getActivity()).onMyButtonClicked();
}
});
}
错误
11-12 23:15:14.115: E/AndroidRuntime(31864): java.lang.ClassCastException: nl.name.projectname.ProjectName cannot be cast to nl.name.projectName.OnFragmentButtonListener
11-12 23:15:14.115: E/AndroidRuntime(31864): at nl.name.projectname.fragments.ParentFragment$LoadInfoTask$1.onClick(ParentFragment.java:323)
11-12 23:15:14.115: E/AndroidRuntime(31864): at android.view.View.performClick(View.java:4445)
11-12 23:15:14.115: E/AndroidRuntime(31864): at android.view.View$PerformClick.run(View.java:18446)
11-12 23:15:14.115: E/AndroidRuntime(31864): at android.os.Handler.handleCallback(Handler.java:733)
11-12 23:15:14.115: E/AndroidRuntime(31864): at android.os.Handler.dispatchMessage(Handler.java:95)
11-12 23:15:14.115: E/AndroidRuntime(31864): at android.os.Looper.loop(Looper.java:136)
11-12 23:15:14.115: E/AndroidRuntime(31864): at android.app.ActivityThread.main(ActivityThread.java:5146)
11-12 23:15:14.115: E/AndroidRuntime(31864): at java.lang.reflect.Method.invokeNative(Native Method)
11-12 23:15:14.115: E/AndroidRuntime(31864): at java.lang.reflect.Method.invoke(Method.java:515)
11-12 23:15:14.115: E/AndroidRuntime(31864): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:796)
11-12 23:15:14.115: E/AndroidRuntime(31864): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:612)
11-12 23:15:14.115: E/AndroidRuntime(31864): at dalvik.system.NativeStart.main(Native Method)
答案 0 :(得分:0)
看起来您正在尝试在父Activity上调用onMyButtonClicked,而不是子FragmentQueue实例。在onClick方法中,您需要获取对FragmentQueue实例的引用,然后调用onMyButtonClicked。像这样:
refresh.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Fragment fragment = getFragmentManager().findFragmentByTag("FragmentQueue");
if (fragment instanceof FragmentQueue) {
((FragmentQueue)fragment).onMyButtonClicked();
}
}
});
请注意,要使其正常工作,您必须将片段标记设置为" FragmentQueue"在构造片段时(使用XML或代码)。