从Activity调用Fragment的方法不行?

Calling Fragment's method from Activity doesn't work?

我关注了 this 问题并尝试调用我的片段中的方法。我正在尝试从 activity 调用该方法。但是它没有识别片段的方法。这是我的代码:

XML:

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/peoplefragment">

    <ListView
        android:id="@+id/searchpeople_list"
        android:layout_height="fill_parent"
        android:layout_width="match_parent"
        android:scrollbars="none"
        android:background="#fff">
    </ListView>

</RelativeLayout>

片段代码:

    public class SearchPeopleTab extends Fragment {

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
        {          
            View v = inflater.inflate(R.layout.activity_search_people_tab, container, false);
            View rootView = inflater.inflate(R.layout.activity_search_people_tab, container, false);
            return rootView;
        }

        public static void UpdateResults(String requestSearch)
        {
               new GetSearchResults(requestSearch).execute();
        }

class GetSearchResults extends AsyncTask<Void, Void, Void> {

        String requestSearch;

        GetSearchResults(String searchtext)
        {
            this.requestSearch = searchtext;
        }

        @Override
        protected Void doInBackground(Void... params) {
    }

Activity代码:(调用Fragment的方法)

 private void PopulateResults() {

        FragmentManager manager = (FragmentManager) getSupportFragmentManager();
        Fragment fragment = manager.findFragmentById(R.id.peoplefragment);
        fragment.UpdateResults(requestSearch); //thats the method in the fragment. 

}

'UpdateResults()' 部分带有下划线,以下消息为错误消息:

Cannot resolve method UpdateResults()

好像找不到方法。我做错了什么?

  1. 从方法中删除关键字 static

  2. 此外,将片段存储在您创建的 SearchPeopleTab 引用变量 中。

    你并不需要存储FragmentManager的行,你可以直接使用getSupportFragmentManager();

    //FragmentManager fm = (FragmentManager) getSupportFragmentManager();
    SearchPeopleTab fragment = (SearchPeopleTab) getSupportFragmentManager().findFragmentById(R.id.peoplefragment);
    fragment.UpdateResults();
    

使用静态方法时,使用 class 名称调用它们。 当您希望在特定对象上调用方法时,该方法不应是静态的。

您需要将 Fragment 转换为您定义的 class

private void PopulateResults() {

    FragmentManager manager = (FragmentManager) getSupportFragmentManager();
    SearchPeopleTab fragment = (SearchPeopleTab)manager.findFragmentById(R.id.peoplefragment);
    fragment.UpdateResults(); //thats the method in the fragment. 

}