我试图通过单击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;
}
}
答案 0 :(得分:2)
看起来问题是你没有FinishPostFragment的构造函数来获取Activity。
由于您始终可以在片段中使用getActivity()
,因此无需在构造函数中将其传递给Activity。
您可以将其更改为:
fm.beginTransaction().replace(R.id.content_main, new FinishPostFragment()).commit();