Mark Murphy - Beginning Android

Здесь есть возможность читать онлайн «Mark Murphy - Beginning Android» весь текст электронной книги совершенно бесплатно (целиком полную версию без сокращений). В некоторых случаях можно слушать аудио, скачать через торрент в формате fb2 и присутствует краткое содержание. Город: New York, Год выпуска: 2009, ISBN: 2009, Издательство: Apress, Жанр: Программирование, на английском языке. Описание произведения, (предисловие) а так же отзывы посетителей доступны на портале библиотеки ЛибКат.

Beginning Android: краткое содержание, описание и аннотация

Предлагаем к чтению аннотацию, описание, краткое содержание или предисловие (зависит от того, что написал сам автор книги «Beginning Android»). Если вы не нашли необходимую информацию о книге — напишите в комментариях, мы постараемся отыскать её.

Master Android from first principles and begin the journey toward your own successful Android applications!
Dear Reader,
First, welcome to the world of Android! We’re entering a new era of mobile application development, one marked by open platforms and open source, to take ‘walled gardens’ and make them green houses for any and all to participate in. Android is relatively easy for developers, and I believe that this innovation will help generate a large ecosystem of developers and consumers within a very short time. This means that budding developers such as yourself will have many opportunities to design and build your own applications and you’ll have a huge and hungry customer base.
Second, welcome to the book! Its purpose is to start you on your way with building Android applications, and to help you master the learning curve. Android is already a rich framework, comparable in many ways to the richness Android of desktop Java environments. This means that there is a lot of cool stuff for you to pick up along your journey in order to create the slickest, most useful apps Android you can imagine.
The source code for the code samples in this book is all available from the Apress site, so you can stay as hands-on and practical as you like while I introduce you to the core of Android, and invite you to experiment with the various classes and APIs we’ll be looking at. By the time you’ve finished this book, you’ll be creating your own Android applications and asking yourself what your next great application will be…!
Enjoy! Mark Murphy

Beginning Android — читать онлайн бесплатно полную книгу (весь текст) целиком

Ниже представлен текст книги, разбитый по страницам. Система сохранения места последней прочитанной страницы, позволяет с удобством читать онлайн бесплатно книгу «Beginning Android», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

}

} catch(java.io.FileNotFoundException e) {

// that's OK, we probably haven't created it yet

} catch(Throwable t) {

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

}

}

publicvoid onPause() {

super. onPause();

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.txtand 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/valuesdirectory (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:

The quick brown fox...

He who laughs last...

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);

String strResult = String. format(strFormat, "Tim");

((TextView) findViewById(R.layout.some_label)). setText(strResult);

Styled Text

If you want really rich text, you should have raw resources containing HTML, then pour those into a WebKit widget. However, for light HTML formatting, using , , and , you can just use a string resource:

This has bold in it.

Whereas this has italics!

You can access these the same as with plain strings, with the exception that the result of the getString()call is really an object supporting the android.text.Spannedinterface:

((TextView) findViewById(R.layout.another_label))

. setText( getString(R.string.laughs));

Styled Formats

Where styled text gets tricky is with styled string formats, as String.format()works on Stringobjects, not Spannedobjects with formatting instructions. If you really want to have styled string formats, here is the workaround:

Читать дальше
Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

Похожие книги на «Beginning Android»

Представляем Вашему вниманию похожие книги на «Beginning Android» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.


Отзывы о книге «Beginning Android»

Обсуждение, отзывы о книге «Beginning Android» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.

x