我正在尝试将数据(我选择的字符串)从listview中的一个片段传递到edittext中的另一个片段。在这种情况下,这怎么可能?
我可以使用捆绑包吗?如果是,怎么样?
第一个片段:
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<>();
@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()).commit();
}
});
searchAirport();
return rootView;
}
SecondFragment:
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;
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.finish_post_button, menu);
}
}
答案 0 :(得分:1)
你应该使用Bundle
这是一个例子
FragmentManager fm = getActivity().getFragmentManager();
Fragment fragment = new FinishPostFragment();
Bundle bundle = new Bundle();
bundle.putString("data", "your string");
fragment.setArgument(bundle);
fm.beginTransaction().replace(R.id.content_main, fragment).commit();
并在你的第二个片段中:
String data = getArguments().getString("data");
并且有一种更清洁的方式。在第二个片段中,添加newInstance
函数:
public static final String DATA_TAG="data";
private String mData;
public static FinishPostFragment newInstance(String data) {
Bundle args = new Bundle();
args.putString(DATA_TAG, data);
FinishPostFragment fragment = new FinishPostFragment();
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null)
mData = getArguments().getString(DATA_TAG);
}
}