我跟着this问题,试着调用我片段中的方法。我正试图从一个活动中调用该方法。然而,它没有识别片段的方法。这是我的代码:
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) {
}
活动代码:(调用片段的方法)
private void PopulateResults() {
FragmentManager manager = (FragmentManager) getSupportFragmentManager();
Fragment fragment = manager.findFragmentById(R.id.peoplefragment);
fragment.UpdateResults(requestSearch); //thats the method in the fragment.
}
'UpdateResults()'部分带有下划线,并显示以下消息:
无法解析方法UpdateResults()
看起来无法找到方法。我做错了什么?
答案 0 :(得分:1)
从方法中删除关键字static
。
此外,将片段存储在您创建的 SearchPeopleTab
引用变量中。
您真的不需要该行来存储FragmentManager
,您可以直接使用getSupportFragmentManager();
//FragmentManager fm = (FragmentManager) getSupportFragmentManager();
SearchPeopleTab fragment = (SearchPeopleTab) getSupportFragmentManager().findFragmentById(R.id.peoplefragment);
fragment.UpdateResults();
使用静态方法时,使用类名调用它们。 如果希望在特定对象上调用方法,则该方法不应该是静态的。
答案 1 :(得分:1)
您需要将Fragment强制转换为已定义的类
private void PopulateResults() {
FragmentManager manager = (FragmentManager) getSupportFragmentManager();
SearchPeopleTab fragment = (SearchPeopleTab)manager.findFragmentById(R.id.peoplefragment);
fragment.UpdateResults(); //thats the method in the fragment.
}