Using a Format String

The last preliminary step is to create a template crime report that can be configured with the specific crime’s details. Because you will not know a crime’s details until runtime, you must use a format string with placeholders that can be replaced at runtime. Here is the format string you will use:

    %1$s! The crime was discovered on %2$s. %3$s, and %4$s

%1$s, %2$s, etc. are placeholders that expect string arguments. In code, you will call getString(…) and pass in the format string and four other strings in the order in which they should replace the placeholders. The result will be a report along the lines of, “Stolen yogurt! The crime was discovered on Wed., May 11. The case is not solved, and there is no suspect.”

First, in strings.xml, add the strings shown in Listing 16.6.

Listing 16.6  Adding string resources (res/values/strings.xml)

<resources>
    ...
    <string name="crime_suspect_text">Choose Suspect</string>
    <string name="crime_report_text">Send Crime Report</string>
    <string name="crime_report">%1$s!
      The crime was discovered on %2$s. %3$s, and %4$s
    </string>
    <string name="crime_report_solved">The case is solved</string>
    <string name="crime_report_unsolved">The case is not solved</string>
    <string name="crime_report_no_suspect">there is no suspect.</string>
    <string name="crime_report_suspect">the suspect is %s.</string>
    <string name="crime_report_subject">CriminalIntent Crime Report</string>
    <string name="send_report">Send crime report via</string>
</resources>

In CrimeDetailFragment.kt, add a function that creates four strings and then pieces them together and returns a complete report.

Listing 16.7  Adding a getCrimeReport(crime: Crime) function (CrimeDetailFragment.kt)

private const val DATE_FORMAT = "EEE, MMM, dd"

class CrimeDetailFragment : Fragment() {
    ...
    private fun updateUi(crime: Crime) {
        ...
    }

    private fun getCrimeReport(crime: Crime): String {
        val solvedString = if (crime.isSolved) {
            getString(R.string.crime_report_solved)
        } else {
            getString(R.string.crime_report_unsolved)
        }

        val dateString = DateFormat.format(DATE_FORMAT, crime.date).toString()
        val suspectText = if (crime.suspect.isBlank()) {
            getString(R.string.crime_report_no_suspect)
        } else {
            getString(R.string.crime_report_suspect, crime.suspect)
        }

        return getString(
            R.string.crime_report,
            crime.title, dateString, solvedString, suspectText
        )
    }
}

(There are multiple DateFormat classes. Make sure you import android.text.format.DateFormat.)

Now the preliminaries are complete, and you can turn to implicit intents.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset