我试图通过单击ListView中的一个项目转到另一个片段(从AirportPostFragment到FinishPostFragment)。
为什么这不起作用?

(getActivity())下划线为红色。

错误:(61,66)错误:类FinishPostFragment中的构造方法FinishPostFragment无法应用于给定类型;不能将其应用于给定类型。
必需:无参数
找到:活动
原因:实际和正式论点清单的长度不同

码:

public class AirportPostFragment extends Fragment {

String stringsList[];
ArrayAdapter<String> adapter;
private ListView listViewAirports;
private EditText editSearch;
Context mycontext;
XmlPullParser parser;
HashSet airport_list;
HashSet<String> list = new HashSet<>();
HashSet<String> newList = new HashSet<>();

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_airportpost, container, false);

    listViewAirports = (ListView) rootView.findViewById(R.id.listView_airports);
    editSearch = (EditText) rootView.findViewById(R.id.search_airport);
    adapter = new ArrayAdapter<>(getActivity(),android.R.layout.simple_list_item_1, stringsList);

    listViewAirports.setAdapter(adapter);


    listViewAirports.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                                long id) {
            FragmentManager fm = getActivity().getFragmentManager();
            fm.beginTransaction().replace(R.id.content_main, new FinishPostFragment(getActivity())).commit();
        }
    });




    searchAirport();

    return rootView;
}


这是我的FinishPostFragment代码:

public class FinishPostFragment extends Fragment {

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_finishpost, container, false);

        return rootView;
    }
}




这是我的FinishPostFragment代码:

public class FinishPostFragment extends Fragment {

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_finishpost, container, false);

    return rootView;
}


}

最佳答案

看来问题在于您没有用于带有Activity的FinishPostFragment的构造函数。
由于您始终可以在Fragment中使用getActivity(),因此无需在构造函数中将其传递给Activity。

您可以将其更改为:

fm.beginTransaction().replace(R.id.content_main, new FinishPostFragment()).commit();

08-04 07:08