在Activity和ListFragment之间进行通信不起作用(类型不兼容)

时间:2019-03-21 20:36:53

标签: android android-fragments callback

试图像在docs中一样在Activity和ListFragment之间进行通信。

但是当我定义接口时:

 public class HeadlinesFragment extends ListFragment {
    OnHeadlineSelectedListener callback;

    public void setOnHeadlineSelectedListener(Activity activity) {
        callback = activity;
    }

    // Container Activity must implement this interface
    public interface OnHeadlineSelectedListener {
        public void onArticleSelected(int position);
    }

我捕获到错误“不兼容的类型”。此处:callback = activity;

UPD:我附在这里:

public class MainActivity extends AppCompatActivity
        implements MainFragment.OnHeadlineSelectedListener {

    @Override
    public void onAttachFragment(Fragment fragment) {
        if (fragment instanceof MainFragment) {
            MainFragment headlinesFragment = (MainFragment) fragment;
            headlinesFragment.setOnHeadlineSelectedListener(this);
        }
    }

    @Override
    public void onArticleSelected(int position) {

        MenuFragment newFragment = new MenuFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("Integer", position);
        newFragment.setArguments(bundle);

    }

2 个答案:

答案 0 :(得分:0)

您正在尝试将OnHeadlineSelectedListener回调强制转换为Activity.class类型。但这是两种不同的类型!您应该将OnHeadlineSelectedListener回调传递给setOnHeadlineSelectedListener()方法,如下所示:

mFirestore = FirebaseFirestore.getInstance()
mFirestore.collection("YOUR COLLECTION")
                .get()
                .addOnCompleteListener { task ->
                    if (task.isSuccessful) {
                        val list = ArrayList<"YOUR OBJECT">()
                        for (document in task.result) {
                            val yourobjectType = document.toObject(YOUR OBJECT::class.java)
                            list.add(yourobjectType)
                        }

                    } else {
                        Log.d(TAG, "Error getting documents: ", task.exception)
                    }
                }

或者您的MainActivity必须实现HeadlinesFragment.OnHeadlineSelectedListener

public void setOnHeadlineSelectedListener(OnHeadlineSelectedListener callback) {
    this.callback = callback;
}

在您的代码中检查它!

答案 1 :(得分:0)

fragment instanceof MainFragment中的内容将不会执行 您的片段是HeadlinesFragment而不是MainFragment

public static class MainActivity extends Activity
        implements HeadlinesFragment.OnHeadlineSelectedListener{
    // ...

    @Override
    public void onAttachFragment(Fragment fragment) {
        if (fragment instanceof HeadlinesFragment) {
            HeadlinesFragment headlinesFragment = (HeadlinesFragment) fragment;
            headlinesFragment.setOnHeadlineSelectedListener(this);
        }
    }
}