如何调用Fragment另一个片段函数

时间:2016-11-27 01:39:46

标签: android

我在Android中创建了一个带有一个MainActivity和两个片段的TabLayout。

但是如何让第二个Fragment接收按钮事件并调用第一个Fragment函数?

我尝试了以下但是它不起作用我问。

public interface CustomSearchPOI {
    void requestSearch(String query);
}

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    try {
        customSearchPOI = (CustomSearchPOI)context;
    } catch (ClassCastException ex) {
        throw new ClassCastException(context.toString() + "must implement CustomSearchPOI");
    }
}

第二段片段代码

if(info_cursor != null) {
        info_cursor.moveToFirst();
        while(!info_cursor.isAfterLast()) {
            if(info_cursor.getInt(0) == id) {
                out_subject.setText(info_cursor.getString(1));
                out_college.setText(info_cursor.getString(2));
                out_classroom.setText(info_cursor.getString(3));
                break;
            }
            info_cursor.moveToNext();
        }
    }
    choice_dialog.setPositiveButton(getString(R.string.Location_navigate), new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            TabsFragment.viewPager.setCurrentItem(0);
            customSearchPOI.requestSearch(out_college.getText().toString());
        }
    });
    choice_dialog.setNegativeButton(getString(R.string.tt_modify), new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            update_timetable_dialog(id);
        }
    });
    choice_dialog.show();

调用功能代码

@Override
public void requestSearch(String query) {
    String FRAGMENT_TAG = "LOCATION_TAG";
    Fragment fragment = new MapFragment();
    FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
    fragmentTransaction.add(fragment, FRAGMENT_TAG).commitAllowingStateLoss();
    try {
        ((MapFragment)getSupportFragmentManager().findFragmentByTag(FRAGMENT_TAG)).searchPOI(query);
    } catch(NullPointerException ex) {
        ex.printStackTrace();
        Log.d("[TAG]", fragment.getTag());
    }
}

MainActivity Code

public void searchPOI(String query) {
    query = Searchcheck(query);
    TMapData data = new TMapData();
    if(!TextUtils.isEmpty(query)) {
        data.findAllPOI(query, new TMapData.FindAllPOIListenerCallback() {
            @Override
            public void onFindAllPOI(final ArrayList<TMapPOIItem> arrayList) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tMapView.removeAllMarkerItem();
                        for (TMapPOIItem poi : arrayList) {
                            addMarker(poi);
                        }
                        if(arrayList.size() > 0) {
                            TMapPOIItem poi = arrayList.get(0);
                            moveMap(poi.getPOIPoint().getLatitude(), poi.getPOIPoint().getLongitude());
                            if(poi.getPOIPoint().getLatitude() > 36.832311 && poi.getPOIPoint().getLongitude() < 127.165038) {
                                Snackbar.make(coordinatorLayout, getString(R.string.No_place), Snackbar.LENGTH_LONG).show();
                                if(location_me.getVisibility() != View.INVISIBLE) {
                                    location_me.hide();
                                }
                                return;
                            }
                            dst = new TMapPoint(poi.getPOIPoint().getLatitude(), poi.getPOIPoint().getLongitude());
                            searchRoute(src, dst);
                        }
                    }
                });
            }
        });
    }
}

第一个片段代码(要调用的函数)

根据Google开发文档,片段和片段之间的直接通信是不可能的。

所以当我尝试通过Activity从Fragment调用Fragment函数时,我得到NullPointerException错误。

我使用了try catch语法来查看标记名称中是否有错误或查询中是否有错误,但它们都不是问题。

1 个答案:

答案 0 :(得分:1)

FragmentX:

max-age

X类:

public class MyFragment extends Fragment{

    interface MyInterface{

       void doSomething();
    }

    public void someMethodInYourFragment(){
     ((MyInterface)getContext()).doSomething();//throws ClassCastException if not implemented in Activity
    }

}