try {

   OutputStreamWriter out =

    new OutputStreamWriter(openFileOutput(NOTES, 0));

   out.write(editor.getText().toString ());

   out.close();

  } catch (Throwable t) {

   Toast.makeText(this, 'Exception: ' + t.toString(), 2000).show();

  }

 }

}

First we wire up the button to close out our activity when it’s clicked, by using setOnClickListener () to invoke finish() on the activity.

Next we hook into onResume() so we get control when our editor is coming to life, from a fresh launch or after having been frozen. We use openFileInput() to read in notes.txt and pour the contents into the text editor. If the file is not found, we assume this is the first time the activity was run (or that the file was deleted by other means), and we just leave the editor empty.

Finally we hook into onPause() so we get control as our activity gets hidden by another activity or is closed, such as via our Close button. Here we use openFileOutput() to open notes.txt, into which we pour the contents of the text editor.

The net result is that we have a persistent notepad: whatever is typed in will remain until deleted, surviving our activity being closed, the phone being turned off, and similar situations.

CHAPTER 19

Working with Resources

Resources are static bits of information held outside the Java source code. You have seen one type of resource — the layout — frequently in the examples in this book. There are many other types of resource, such as images and strings, that you can take advantage of in your Android applications.

The Resource Lineup

Resources are stored as files under the res/ directory in your Android project layout. With the exception of raw resources (res/raw/), all the other types of resources are parsed for you, either by the Android packaging system or by the Android system on the device or emulator. For example, when you lay out an activity’s UI via a layout resource (res/layout/), you do not have to parse the layout XML yourself — Android handles that for you.

In addition to layout resources (first seen in Chapter 5) and raw resources (introduced in Chapter 18), there are several other types of resources available to you, including:

• Animations (res/anim/), designed for short clips as part of a user interface, such as an animation suggesting the turning of a page when a button is clicked

• Images (res/drawable), for putting static icons or other pictures in an user interface

• Strings, colors, arrays, and dimensions (res/values/), to both give these sorts of constants symbolic names and to keep them separate from the rest of the code (e.g., for internationalization and localization)

• XML (res/xml/), for static XML files containing your own data and structure

String Theory

Keeping your labels and other bits of text outside the main source code of your application is generally considered to be a very good idea. In particular, it helps with internationalization (I18N) and localization (L10N), covered in the section “Different Strokes for Different Folks” later on in this chapter. Even if you are not going to translate your strings to other languages, it is easier to make corrections if all the strings are in one spot instead of scattered throughout your source code.

Android supports regular externalized strings, along with “string formats”, where the string has placeholders for dynamically-inserted information. On top of that, Android supports simple text formatting, called “styled text”, so you can make your words be bold or italic intermingled with normal text.

Plain Strings

Generally speaking, all you need to have for plain strings is an XML file in the res/values directory (typically named res/values/strings.xml), with a resources root element, and one child string element for each string you wish to encode as a resource. The string element takes a name attribute, which is the unique name for this string, and a single text element containing the text of the string:

<resources>

 <string name='quick'>The quick brown fox...</string>

 <string name='laughs'>He who laughs last...</string>

</resources>

The only tricky part is if the string value contains a quote (') or an apostrophe ('). In those cases, you will want to escape those values, by preceding them with a backslash (e.g., These are the times that try men's souls). Or, if it is just an apostrophe, you could enclose the value in quotes (e.g., 'These are the times that try men's souls.').

You can then reference this string from a layout file (as @string/..., where the ellipsis is the unique name — e.g., @string/laughs). Or you can get the string from your Java code by calling getString() with the resource ID of the string resource, that being the unique name prefixed with R.string. (e.g., getString(R.string.quick)).

String Formats

As with other implementations of the Java language, Android’s Dalvik VM supports string formats. Here, the string contains placeholders representing data to be replaced at runtime by variable information (e.g., My name is %1$s). Plain strings stored as resources can be used as string formats:

String strFormat = getString(R.string.my_name);

Вы читаете Beginning Android
Добавить отзыв
ВСЕ ОТЗЫВЫ О КНИГЕ В ИЗБРАННОЕ

0

Вы можете отметить интересные вам фрагменты текста, которые будут доступны по уникальной ссылке в адресной строке браузера.

Отметить Добавить цитату