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», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

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

Интервал:

Закладка:

Сделать

private void updateTime() {

btn.setText(new Date().toString());

}

When we open the activity ( onCreate()) or when the button is clicked ( onClick()), we update the button’s label to be the current time via setText(), which functions much the same in Android as JButtondoes in Swing.

Building and Running the Activity

To build the activity, either use your IDE’s built-in Android packaging tool, or run ant in the base directory of your project. Then, to run the activity do the following:

1. Launch the emulator (e.g., run tools/emulatorfrom your Android SDK installation), as shown in Figure 4-1.

Figure 41 The Android home screen 2 Install the package eg run - фото 2

Figure 4-1. The Android home screen

2. Install the package (e.g., run tools/adb install /path/to/this/example/bin/Now.apkfrom your Android SDK installation).

3. View the list of installed applications in the emulator and find the Now application (see Figure 4-2).

Figure 42 The Android application launcher 4 Open that application You - фото 3

Figure 4-2. The Android application “launcher”

4. Open that application.

You should see an activity screen like the one shown in Figure 4-3.

Figure 43 The Now demonstration activity Clicking the button in other - фото 4

Figure 4-3. The Now demonstration activity

Clicking the button — in other words, clicking pretty much anywhere on the phone’s screen — will update the time shown in the button’s label.

Note that the label is centered horizontally and vertically, as those are the default styles applied to button captions. We can control that formatting, which Chapter 6 covers.

After you are done gazing at the awesomeness of Advanced Push-Button Technology, you can click the back button on the emulator to return to the launcher.

CHAPTER 5

Using XML-Based Layouts

While it is technically possible to create and attach widgets to our activity purely through Java code, the way we did in Chapter 4, the more common approach is to use an XML-based layout file. Dynamic instantiation of widgets is reserved for more complicated scenarios, where the widgets are not known at compile-time (e.g., populating a column of radio buttons based on data retrieved off the Internet).

With that in mind, it’s time to break out the XML and learn how to lay out Android activities that way.

What Is an XML-Based Layout?

As the name suggests, an XML-based layout is a specification of widgets’ relationships to each other — and to their containers (more on this in Chapter 7) — encoded in XML format. Specifically, Android considers XML-based layouts to be resources, and as such layout files are stored in the res/layoutdirectory inside your Android project.

Each XML file contains a tree of elements specifying a layout of widgets and their containers that make up one view hierarchy. The attributes of the XML elements are properties, describing how a widget should look or how a container should behave. For example, if a Buttonelement has an attribute value of android:textStyle = "bold", that means that the text appearing on the face of the button should be rendered in a boldface font style.

Android’s SDK ships with a tool ( aapt) which uses the layouts. This tool should be automatically invoked by your Android tool chain (e.g., Eclipse, Ant’s build.xml). Of particular importance to you as a developer is that aaptgenerates the R.javasource file within your project, allowing you to access layouts and widgets within those layouts directly from your Java code.

Why Use XML-Based Layouts?

Most everything you do using XML layout files can be achieved through Java code. For example, you could use setTypeface()to have a button render its text in bold, instead of using a property in an XML layout. Since XML layouts are yet another file for you to keep track of, we need good reasons for using such files.

Perhaps the biggest reason is to assist in the creation of tools for view definition, such as a GUI builder in an IDE like Eclipse or a dedicated Android GUI designer like DroidDraw [8] http://droiddraw.org/ . Such GUI builders could, in principle, generate Java code instead of XML. The challenge is re-reading the UI definition to support edits—that is far simpler if the data is in a structured format like XML than in a programming language. Moreover, keeping generated XML definitions separated from hand-written Java code makes it less likely that somebody’s custom-crafted source will get clobbered by accident when the generated bits get re-generated. XML forms a nice middle ground between something that is easy for tool-writers to use and easy for programmers to work with by hand as needed.

Also, XML as a GUI definition format is becoming more commonplace. Microsoft’s XAML [9] http://windowssdk.msdn.microsoft.com/en-us/library/ms752059.aspx , Adobe’s Flex [10] http://www.adobe.com/products/flex/ , and Mozilla’s XUL [11] http://www.mozilla.org/projects/xul/ all take a similar approach to that of Android: put layout details in an XML file and put programming smarts in source files (e.g., JavaScript for XUL). Many less-well-known GUI frameworks, such as ZK [12] http://www.zkoss.org/ , also use XML for view definition. While “following the herd” is not necessarily the best policy, it does have the advantage of helping to ease the transition into Android from any other XML-centered view description language.

OK, So What Does It Look Like?

Here is the Buttonfrom the previous chapter’s sample application, converted into an XML layout file, found in the Layouts/NowReduxsample project. This code sample along with all others in this chapter can be found in the Source Code area of http://apress.com.

android:id="@+id/button"

android:text=""

android:layout_width="fill_parent"

android:layout_height="fill_parent"/>

The class name of the widget — Button— forms the name of the XML element. Since Buttonis an Android-supplied widget, we can just use the bare class name. If you create your own

widgets as subclasses of android.view.View, you would need to provide a full package declaration as well (e.g., com.commonsware.android.MyWidget).

The root element needs to declare the Android XML namespace:

xmlns:android="http://schemas.android.com/apk/res/android"

All other elements will be children of the root and will inherit that namespace declaration.

Because we want to reference this button from our Java code, we need to give it an identifier via the android:idattribute. We will cover this concept in greater detail later in this chapter.

The remaining attributes are properties of this Buttoninstance:

android:textindicates the initial text to be displayed on the button face (in this case, an empty string)

android:layout_widthand android:layout_heighttell Android to have the button’s width and height fill the “parent”, in this case the entire screen — these attributes will be covered in greater detail in Chapter 7.

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

Интервал:

Закладка:

Сделать

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

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


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

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

x