Reputation: 1082
I have 2 fragment hosted on an activity with a frame layout, I want to implement fragment communication.I have tried some of the codes, but my requirements are not met. Thanks in advance.!
First fragment: It contains a list .
public class ListWithSearch extends Fragment{
String[] cityName;
String[] cityFact;
int[] cityPic;
ListView list;
ListViewAdapter adapter;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.city_list_fragment, container,
false);
// Generate sample data
cityName = new String[] { "Delhi", "Chandigarh", "Mumbai", "Bangalore", "Chennai" };
cityFact = new String[] { "China", "India", "United States",
"Indonesia", "Brazil" };
cityPic = new int[] { R.drawable.ic_launcher, R.drawable.ic_launcher,
R.drawable.ic_launcher, R.drawable.ic_launcher,
R.drawable.ic_launcher };
list = (ListView) rootView.findViewById(R.id.listView);
adapter = new ListViewAdapter(getActivity(), cityName,cityPic);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//To implement
}
});
return rootView;
}
}
Second Fragment: That will be inflated on item click of the list in the first fragment.
public class ResultFragment extends Fragment {
TextView resCityName;
TextView resFact;
ImageView resPic;
String[] cityName;
String[] cityFact;
int[] cityPic;
int position;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return super.onCreateView(inflater, container, savedInstanceState);
}
}
Requirements: 1. ImageView in second fragment to have the same image of the item image in the list. 2. TextViews in second fragment to have data from the list item itself.
In other words, the second fragment is details of the item clicked in the list.
Upvotes: 0
Views: 60
Reputation: 878
Add the below code to ListWithSearch
fragment:
OnListItemSelectListener mCallback;
// Your MainActivity must implement this interface so that ResultFragment can use it
public interface OnListItemSelectListener {
public void onItemSelected(int position, int imageId);
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallback = (OnListItemSelectListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnListItemSelectListener");
}
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
// Send the event to the host activity
// You can pass the image id to below method. Modify the code as required.
mCallback.onItemSelected(position, imageId);
}
Upvotes: 1