0

FragmentHost имеет ViewPager, а фрагменты данных viewpager - от FragmentHost, чтобы создать их виды.Как фрагмент в фрагментеStatePagerAdapter получает данные из Фрагмента, на котором размещается viewPager?

Как получить данные. Данные являются обычным классом.

Один из способов: использование Serializable реализации пользовательского класса. Но я хочу избежать этого, поскольку класс содержит массив и карту других пользовательских классов.

Также может быть несколько экземпляров FragmentHost активных за один раз, один FragmentHost за активность.

ответ

-1

Проверить это для связи

public class CrimePagerActivity extends AppCompatActivity { 

    private static final String EXTRA_CRIME_ID = "com.android.ankitt.criminalintent.activities.extra.crime.id"; 

    private ViewPager mViewPager; 
    private List<Crime> mCrimes; 


    public static Intent newIntent(Context packageContext, UUID crimeId) { 

     Intent intent = new Intent(packageContext, CrimePagerActivity.class); 
     intent.putExtra(EXTRA_CRIME_ID, crimeId); 
     return intent; 
    } 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_crime_pager); 


     UUID crimeId = (UUID) getIntent().getSerializableExtra(EXTRA_CRIME_ID); 

     mViewPager = (ViewPager) findViewById(R.id.actvity_crime_pager_view_pager); 
     mCrimes = CrimeLab.get(this).getCrimes(); 

     FragmentManager manager = getSupportFragmentManager(); 

     mViewPager.setAdapter(new FragmentPagerAdapter(manager) { 
      @Override 
      public Fragment getItem(int position) { 
       Crime crime = mCrimes.get(position); 

       return CrimeFragment.newInstance(crime.getId()); 
      } 

      @Override 
      public int getCount() { 
       return mCrimes.size(); 
      } 
     }); 

     for (int i = 0; i < mCrimes.size(); i++) { 

      if (mCrimes.get(i).getId().equals(crimeId)) { 

       mViewPager.setCurrentItem(i); 
       break; 
      } 
     } 

    } 
} 

Фрагмент

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(@Nullable Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     /*mCrime = new Crime();*/ 


     /*UUID crimeId = (UUID)getActivity().getIntent().getSerializableExtra(CrimeActivity.EXTRA_CRIME_ID);*/ 
     UUID crimeId = (UUID) getArguments().getSerializable(ARG_CRIME_ID); 

     mCrime = CrimeLab.get(getActivity()).getCrime(crimeId); 

     mFilePhoto = CrimeLab.get(getActivity()).getPhotoFile(mCrime); 
    } 

    @Nullable 
    @Override 
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { 
     View view = inflater.inflate(R.layout.fragment_crime, container, false); 

     mEditText = (EditText) view.findViewById(R.id.crime_title); 
     mEditText.setText(mCrime.getTitile()); //Updating Crime fragment with crime 
     mEditText.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) { 

       mCrime.setTitile(toString()); 
      } 

      @Override 
      public void afterTextChanged(Editable s) { 

      } 
     }); 


     final Intent pickContact = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI); 
     /*pickContact.addCategory(Intent.CATEGORY_HOME);*/ 
     mSuspectButton = (Button) view.findViewById(R.id.crime_suspect); 

     mSuspectButton.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       startActivityForResult(pickContact, REQUEST_CONTACT); 
      } 
     }); 

     mReportButton = (Button) view.findViewById(R.id.crime_report); 

     mReportButton.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 

       Intent intent = new Intent(Intent.ACTION_SEND); 
       intent.setType("text/plain"); 
       intent.putExtra(Intent.EXTRA_TEXT, getCrimeReport()); 
       intent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.crime_report_subject)); 
       intent = Intent.createChooser(intent, getString(R.string.send_report)); 
       startActivity(intent); 
      } 
     }); 

     mDateButton = (Button) view.findViewById(R.id.crime_date); 
     updateDate((mCrime.getDate()).toString()); 
     /*mDateButton.setEnabled(false);*/ 
/* Design a date picker for an application */ 
     mDateButton.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       FragmentManager fragmentManager = getFragmentManager(); 
       /*DatePickerFragment dialog = new DatePickerFragment();*/ 

       DatePickerFragment dialog = DatePickerFragment.newInstance(mCrime.getDate()); 

       dialog.setTargetFragment(CrimeFragment.this, REQUEST_DATE); 

       dialog.show(fragmentManager, DIALOG_DATE); 
      } 
     }); 

     mCheckBox = (CheckBox) view.findViewById(R.id.crime_solved); 
     mCheckBox.setChecked(mCrime.isSolved()); //Updating Crime fragment with crime 
     mCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { 
      @Override 
      public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { 
       mCrime.setSolved(isChecked); 
      } 
     }); 

     if (mCrime.getSuspect() != null) { 

      mSuspectButton.setText(mCrime.getSuspect()); 
     } 

     PackageManager packageManager = getActivity().getPackageManager(); 
     if (packageManager.resolveActivity(pickContact, PackageManager.MATCH_DEFAULT_ONLY) == null) { 
      mSuspectButton.setEnabled(false); 
     } 


     mImageButton = (ImageButton) view.findViewById(R.id.crime_camera); 
     final Intent captureImage = new Intent(MediaStore.ACTION_IMAGE_CAPTURE) ; 
     boolean canTakePhoto = mFilePhoto != null && 
       captureImage.resolveActivity(packageManager)!=null; 
     mImageButton.setEnabled(canTakePhoto); 

     if (canTakePhoto){ 

      Uri uri = Uri.fromFile(mFilePhoto); 
      captureImage.putExtra(MediaStore.EXTRA_OUTPUT,uri); 
     } 

     mImageButton.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       startActivityForResult(captureImage,REQUEST_PHOTO); 
      } 
     }); 
     mImageView = (ImageView) view.findViewById(R.id.crime_photo); 
     updatePhotoView(); 
     return view; 
    } 

    public void returnResult() { 
     getActivity().setResult(Activity.RESULT_OK, null); 
    } 


    @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(mCrime.getDate().toString()); 
     } else if (requestCode == REQUEST_CONTACT && data != null) { 

      Uri contactUri = data.getData(); 

      String[] queryFields = new String[]{ 
        ContactsContract.Contacts.DISPLAY_NAME 
      }; 

      Cursor cursor = getActivity().getContentResolver().query(contactUri, queryFields, null, null, null); 
      try { 
       if (cursor.getCount() == 0) { 
        return; 
       } 

       cursor.moveToFirst(); 
       String suspect = cursor.getString(0); 
       mCrime.setSuspect(suspect); 
       mSuspectButton.setText(suspect); 
      } finally { 
       cursor.close(); 
      } 
     }else if (requestCode == REQUEST_PHOTO){ 
      updatePhotoView(); 
     } 
    } 

    private void updateDate(String text) { 
     mDateButton.setText(text); 
    } 

    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, MM 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.getTitile(), dateString, solvedString, suspect); 
     return report; 
    } 

    @Override 
    public void onPause() { 
     super.onPause(); 


     CrimeLab.get(getActivity()).updateCrime(mCrime); 
    } 

    private void updatePhotoView() { 
     if (mFilePhoto == null || !mFilePhoto.exists()) { 
      mImageView.setImageDrawable(null); 
     } else { 
      Bitmap bitmap = PictureUtils.getScaledBitmap(
        mFilePhoto.getPath(), getActivity()); 
      mImageView.setImageBitmap(bitmap); 
     } 
    } 

} 

 Смежные вопросы

  • Нет связанных вопросов^_^