简体   繁体   English

无法从片段内的接口获取数据

[英]Unable to get data from an interface inside a fragment

I have implemented a custom interface for passing data like below:我已经实现了一个自定义接口来传递数据,如下所示:

public interface OnLectureSelected {
    public void lectureSelected(String videoId,String lectureDescription);
}

in the adapter, I am then using the interface to pass data to the activity & the fragment:在适配器中,然后我使用接口将数据传递给活动和片段:

OnLectureSelected onLectureSelected2 = (OnLectureSelected) context;
onLectureSelected2.lectureSelected(video,description);

The activity is able to receive the data as expected:活动能够按预期接收数据:

class Activity extends AppCompatActivity implements OnLectureSelected{
  …
 @Override
 public void lectureSelected(String videoId, String lectureDescription) {
  //I get the passed details
 }

However, I am unable to get the data using a fragment:但是,我无法使用片段获取数据:

class Fragment extends Fragment implements OnLectureSelected{
  …
 @Override
 public void lectureSelected(String videoId, String lectureDescription) {
  //Can't get the passed details
 }

What is the best approach to get the data from the interface inside the fragment?从片段内的接口获取数据的最佳方法是什么?

OnLectureSelected onLectureSelected2 = (OnLectureSelected) context;

Here this object will pass the value to only one implemented class.在这里,这个 object 只会将值传递给一个已实现的 class。 To pass the value to fragments you can call the below method in your Activity class要将值传递给片段,您可以在Activity class 中调用以下方法

@Override
    public void lectureSelected(String videoId, String lectureDescription) {
        //Can't get the passed details
        List<Fragment> fragments = getSupportFragmentManager().getFragments();
        if (fragments != null) {
            for (Fragment fragment : fragments) {
                if(fragment instanceof FragmentClasas) {
                    fragment.lectureSelected(video,description);
                }
            }
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM