fragment互相间的数据传递
之前在实现activity之间基于fragment的activity之间的数据传递,现在要实现同一个activity间托管的两个fragment的数据间的传递。
我们要实现这两个数据的传递需要新建一个方法,将其作为argument传给fragment。
1. DatePickerFragment
public class DatePickerFragment extends DialogFragment {
public static final String EXTRA_DATE=
"edu.niit.android.criminalintent.date";
private static final String ARG_DATE = "date";
private DatePicker mDatePicker;
public static DatePickerFragment newInstance(Date date){
Bundle args = new Bundle();
args.putSerializable(ARG_DATE,date);
DatePickerFragment fragment = new DatePickerFragment();
fragment.setArguments(args);
return fragment;//新建的方法
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState){
//获取Date对象并初始化DatePicker
Date date = (Date) getArguments().getSerializable(ARG_DATE);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day= calendar.get(Calendar.DAY_OF_MONTH);
//添加DatePicker
View v = LayoutInflater.from(getActivity())
.inflate(R.layout.dialog_date, null);
mDatePicker = (DatePicker) v.findViewById(R.id.dialog_date_picker);
mDatePicker.init(year,month,day,null);
return new AlertDialog.Builder(getActivity())
.setView(v)
.setTitle(R.string.date_picker_title)
.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialog, int which){
int year = mDatePicker.getYear();
int month = mDatePicker.getMonth();
int day = mDatePicker.getDayOfMonth();
Date date = new GregorianCalendar(year,month,day).getTime();
sendResult(Activity.RESULT_OK,date);
}
})
.create();
}
//回调目标fragment
private void sendResult(int resultCode, Date date){
if(getTargetFragment()==null){
return;
}
Intent intent = new Intent();
intent.putExtra(EXTRA_DATE,date);
getTargetFragment()
.onActivityResult(getTargetRequestCode(),resultCode,intent);
}
}
CrimeFragment
public class CrimeFragment extends Fragment {
private static final String ARG_CRIME_ID="crime_id";
private static final String DIALOG_DATE="DialogDate";
private static final int REQUEST_DATE=0;//设置目标fragment
private static final int REQUEST_CONTACT=1;
private static final int REQUEST_PHOTO=2;
private Crime mCrime;
private File mPhotoFile;
private EditText mTitleField;
private Button mDataButton;
private CheckBox mSolvedCheckBox;
private Button mReportButton;
private Button mSuspectButton;
private ImageButton mPhotoButton;
private ImageView mPhotoView;
public static CrimeFragment newInstance(UUID crimeId){
Bundle args = new Bundle();
args.putSerializable(ARG_CRIME_ID,crimeId);
CrimeFragment fragment = new CrimeFragment();
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
UUID crimeId = (UUID) getArguments().getSerializable(ARG_CRIME_ID);
mCrime = CrimeLab.get(getActivity()).getCrime(crimeId);
mPhotoFile = CrimeLab.get(getActivity()).getPhotoFile(mCrime);
}
@Override
public void onPause(){
super.onPause();
CrimeLab.get(getActivity())
.updateCrime(mCrime);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState){
View v = inflater.inflate(R.layout.fragment_crime, container, false);
mTitleField = (EditText)v.findViewById(R.id.crime_title);
mTitleField.setText(mCrime.getTitle());
mTitleField.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
mDataButton=(Button)v.findViewById(R.id.crime_data);
mDataButton.setText(mCrime.getDate().toString());
mDataButton.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
FragmentManager manager = getFragmentManager();
DatePickerFragment dialog = DatePickerFragment
.newInstance(mCrime.getDate());//添加方法
dialog.setTargetFragment(CrimeFragment.this,REQUEST_DATE);
dialog.show(manager, DIALOG_DATE);
}
});
mSolvedCheckBox = (CheckBox)v.findViewById(R.id.crime_solved);
mSolvedCheckBox.setChecked(mCrime.isSolved());
mSolvedCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
mCrime.setSolved(isChecked);
}
});
mReportButton=(Button) v.findViewById(R.id.crime_report);
mReportButton.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
Intent i=new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra(Intent.EXTRA_TEXT,getCrimeReport());
i.putExtra(Intent.EXTRA_SUBJECT,
getString(R.string.crime_report_subject));
i=Intent.createChooser(i,getString(R.string.send_report));
startActivity(i);
}
});
final Intent pickContact = new Intent(Intent.ACTION_PICK,
ContactsContract.Contacts.CONTENT_URI);
mSuspectButton=(Button) v.findViewById(R.id.crime_suspect);
mSuspectButton.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
startActivityForResult(pickContact,REQUEST_CONTACT);
}
});
if (mCrime.getSuspect()!=null){
mSuspectButton.setText(mCrime.getSuspect());
}
PackageManager packageManager = getActivity().getPackageManager();
if (packageManager.resolveActivity(pickContact,
PackageManager.MATCH_DEFAULT_ONLY)==null){
mSuspectButton.setEnabled(false);
}
mPhotoButton=(ImageButton) v.findViewById(R.id.crime_camera);
final Intent captureImage = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
boolean canTakePhoto = mPhotoFile !=null&&captureImage.resolveActivity(packageManager)!=null;
mPhotoButton.setEnabled(canTakePhoto);
mPhotoButton.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
Uri uri = FileProvider.getUriForFile(getActivity(),
"edu.niit.android.criminalintent.fileprovider",mPhotoFile);
captureImage.putExtra(MediaStore.EXTRA_OUTPUT,uri);
List<ResolveInfo> cameraActivities=getActivity()
.getPackageManager().queryIntentActivities(captureImage,
PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo activity : cameraActivities){
getActivity().grantUriPermission(activity.activityInfo.packageName,
uri,Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
}
startActivityForResult(captureImage,REQUEST_PHOTO);
}
});
mPhotoView=(ImageView) v.findViewById(R.id.crime_photo);
return v;
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
if (resultCode!=Activity.RESULT_OK){
return;
}
if (requestCode==REQUEST_DATE){
Date date = (Date) data
.getSerializableExtra(DatePickerFragment.EXTRA_DATE);
mCrime.setDate(date);
updateDate();//使用updateDate私有方法
}else if(requestCode==REQUEST_CONTACT&& data !=null){
Uri contactUri = data.getData();
String[] queryFields = new String[]{
ContactsContract.Contacts.DISPLAY_NAME
};
Cursor c = getActivity().getContentResolver()
.query(contactUri,queryFields,null,null,null);
try {
if (c.getCount()==0){
return;
}
c.moveToFirst();
String suspect = c.getString(0);
mCrime.setSuspect(suspect);
mSuspectButton.setText(suspect);
}finally {
c.close();
}
}
}
private void updateDate() {
mDataButton.setText(mCrime.getDate().toString());//高亮选取日期按钮更新代码
}//相应DatePicker对话框
private String getCrimeReport(){
String solvedString =null;
if(mCrime.isSolved()){
solvedString= getString(R.string.crime_report_solved);
}else {
solvedString=getString(R.string.crime_report_unsolved);
}
String dateFormat = "EEE, MMM dd";
String dateString = DateFormat.format(dateFormat,mCrime.getDate()).toString();
String suspect = mCrime.getSuspect();
if (suspect==null){
suspect = getString(R.string.crime_report_no_suspect);
}else {
suspect=getString(R.string.crime_report_suspect,suspect);
}
String report = getString(R.string.crime_report,
mCrime.getTitle(), dateString, solvedString,suspect);
return report;
}
}
SingleFragmentActivity
public abstract class SingleFragmentActivity extends AppCompatActivity{
protected abstract Fragment createFragment();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragment);
FragmentManager fm = getSupportFragmentManager();
Fragment fragment = fm.findFragmentById(R.id.fragment_container);
if(fragment == null){
fragment = new CrimeFragment();
fm.beginTransaction()
.add(R.id.fragment_container, fragment)
.commit();
}
}
}
运行结果