如何在Fragment中使用接口?

时间:2019-04-17 13:17:43

标签: android android-fragments interface android-dialogfragment dialogfragment

我是一位资深的程序员

我有一个DialogFragmentDialogFragment有一个interface

public class FragmentEditClass extends DialogFragment
{
    //. . .


    public interface NotifyChanged
    {
        void updateRemoveClass(int position);
    }
}

我在“片段”选项卡中使用了界面:

public class SecondTab extends Fragment implements FragmentEditClass.NotifyChanged
{
    //. . .

    @Override
    public void updateRemoveClass(int position) 
    {
       //. . .
    }
}

我在适配器中显示DialogFragment

FragmentEditClass.newInstance(classId , className , position)
    .show(secondTab.getFragmentManager() , "DialogFragmentClass");

我想通过以下方式在fragmentTab中的interfaceDialogFragment之间进行通信:

public class FragmentEditClass extends DialogFragment
{
    private NotifyChanged notifyChanged;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        notifyChanged = (NotifyChanged) getActivity();//This line
    }
}

现在的问题是getActivity()。此方法引用SecondTab,但是SecondTab在MainActivity中,我需要引用MainAcitvity。

MyError:

java.lang.ClassCastException: com.example.user.classmanager.MainActivity cannot be cast to com.example.user.classmanager.FragmentEditClass$NotifyChanged
    at com.example.user.classmanager.FragmentEditClass.onCreate(FragmentEditClass.java:91)

0 个答案:

没有答案