Reputation: 133
I am working through exercises in Android Programming: The Big Nerd Ranch Guide (3rd Edition) and I am not sure if my implementation is good or not.
I have two fragments, CrimeListActivity and CrimeActivity which host CrimeListFragment, and CrimeFragment respectively. CrimeFragment contains list of crimes and when user click an item in the list, it will open CrimeActivity (contains CrimeFragment.)
This is code in ViewHodler where I open a new CrimeActivity
@Override
public void onClick(View view) {
Intent intent = CrimeActivity.newIntent(getActivity(), mCrime.getId());
startActivityForResult(intent, REQUEST_CRIME_CODE);
mListener.changed(mCrime);
}
Inside CrimeFragment, I setup a click listener like below.
mDateButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra(REQUEST_CRIME, mCrime.getId());
getActivity().setResult(REQUEST_CRIME_CODE, intent);
}
});
I override onActivityResult in CrimeListFragment so it gets notified when there are changes.
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CRIME_CODE) {
UUID crimeId = (UUID) data.getSerializableExtra(REQUEST_CRIME);
int position = -1;
for (Crime crime : mCrimes) {
position++;
if (crimeId.equals(crime.getId())) {
mAdapter.notifyItemChanged(position);
}
}
}
}
I am not sure if this is the right way of sending data between Fragments as I have Adapter and ViewHolder. Should I put my logic in ViewHolder instead? Is there a better way of doing this?
Upvotes: 2
Views: 95
Reputation: 5017
You can achieve this by avoiding an extra activity i.e, by using only CrimeActivity , CrimeListFragment and CrimeFragment
Initially load the CrimeListFragment
with a listview
inside the CrimeActivity
. Then on the listview click, load the second fragment in the same activity (by using a callback i.e, fragment interaction listener)
In this way the two fragments can be loaded within a single activity itself
Upvotes: 1