I am trying to go to another fragment(from AirportPostFragment to FinishPostFragment) by clicking on an item in a ListView. Why does this not work?
(getActivity()) is underlined red.
Error:(61, 66) error: constructor FinishPostFragment in class FinishPostFragment cannot be applied to given types; required: no arguments found: Activity reason: actual and formal argument lists differ in length
Code:
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;
}
This my code of 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;
}
}
This my code of 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;
}
}
It looks like the issue is that you don't have a constructor for FinishPostFragment that takes an Activity. Since you can always use getActivity()
in a Fragment, there is no need to pass it an Activity in the constructor.
You could just change it to this:
fm.beginTransaction().replace(R.id.content_main, new FinishPostFragment()).commit();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.