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

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

Интервал:

Закладка:

Сделать

...

At the time of this writing, there are two possible minSdkVersionvalues:

• 1, indicating the original Android 1.0 SDK

• 2, indicating the Android 1.1 SDK

If you leave the uses-sdkelement out entirely, it will behave as though minSdkVersionis set to 1.

If you set uses-sdk, the application will install only on compatible devices. You do not have to specify the latest SDK, but if you choose an older one, it is up to you to ensure your application works on every SDK version you claim is compatible. For example, if you leave off uses-sdk, in effect you are stipulating that your application works on every Android SDK version ever released, and it is up to you to test your application to determine if this is indeed the case.

PART 2

Activities

CHAPTER 4

Creating a Skeleton Application

Every programming-language or -environment book starts off with the ever-popular “Hello, World!” demonstration: just enough of a program to prove you can build things, not so much

that you cannot understand what is going on. However, the typical “Hello, World!” program has no interactivity (that is, it just dumps the words to a console), and so is really boring.

This chapter demonstrates a simple project, but one using Advanced Push-Button Technology and the current time to show you how a simple Android activity works.

Begin at the Beginning

To work with anything in Android, you need a project. With ordinary Java, if you wanted, you could just write a program as a single file, compile it with javac, and run it with java, without any other support structures. Android is more complex, but to help keep it manageable Google has supplied tools to help create the project. If you are using an Android-enabled IDE, such as Eclipse with the Android plugin (available in the Android SDK), you can create a project inside of the IDE (select File→New→Project, then choose Android→Android Project).

If you are using tools that are not Android-enabled, you can use the activitycreatorscript, found in the tools/directory in your SDK installation. Just pass activitycreatorthe package name of the activity you want to create and an --outswitch indicating where the project files should be generated. Here’s an example:

activitycreator --out /path/to/my/project/dir \

com.commonsware.android.Now

You will wind up with a handful of pre-generated files, as described in Chapter 2. We’ll be using these files for the rest of this chapter.

You can also download the project directories of the samples shown in this book in a ZIP file on the CommonsWare Web site [6] http://commonsware.com/Android/ . These projects are ready for use; you do not need to run activitycreatoron those unpacked samples.

The Activity

Your project’s src/ directory contains the standard Java-style tree of directories based upon the Java package you used when you created the project (i.e., com.commonsware.androidresulted in src/com/commonsware/android/). Inside the innermost directory you should find a pregenerated source file named Now.java, which is where your first activity will go. This activity will contain a single button that displays the time the button was last pushed (or the time the application was started if the button hasn’t been pushed).

Open Now.javain your editor and paste in the following code:

package com.commonsware.android.skeleton;

import android.app.Activity;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

import java.util.Date;

public class Now extends Activity implements View.OnClickListener {

Button btn;

@Override

public void onCreate(Bundle icicle) {

super.onCreate(icicle);

btn = new Button(this);

btn.setOnClickListener(this);

updateTime();

setContentView(btn);

}

public void onClick(View view) {

updateTime();

}

private void updateTime() {

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

}

}

Or, if you download the source files off the CommonsWare Web site, you can just use the Skeleton/Nowproject directly.

Let’s examine this piece-by-piece.

Dissecting the Activity

The package declaration needs to be the same as the one you used when creating the project. And, like in any other Java project, you need to import any classes you reference. Most of the Android-specific classes are in the androidpackage:

package com.commonsware.android.skeleton;

import android.app.Activity;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

import java.util.Date;

It’s worth noting that not every Java SE class is available to Android programs. Visit the Android class reference [7] http://code.google.com/android/reference/packages.html to see what is and is not available.

Activities are public classes, inheriting from the android.app.Activitybase class. In this case, the activity holds a button ( btn):

public class Now extends Activity implements View.OnClickListener {

Button btn;

Note

A button, as you can see from the package name, is an Android widget, and widgets are the UI elements that you use in your application.

Since, for simplicity, we want to trap all button clicks just within the activity itself, we also have the activity class implement OnClickListener.

@Override

public void onCreate(Bundle icicle) {

super.onCreate(icicle);

btn = new Button(this);

btn.setOnClickListener(this);

updateTime();

setContentView(btn);

}

The onCreate()method is invoked when the activity is started. The first thing you should do is chain upward to the superclass, so the stock Android activity initialization can be done.

In our implementation, we then create the button instance ( new Button(this)), tell it to send all button clicks to the activity instance itself (via setOnClickListener()), call a private updateTime()method (discussed in a moment), and then set the activity’s content view to be the button itself (via setContentView()).

Note

All widgets extend the View base class. We usually build the UI out of a hierarchy of views, but in this example we are using a single view.

I discuss that magical Bundle iciclein Chapter 16. For the moment, consider it an opaque handle that all activities receive upon creation.

public void onClick(View view) {

updateTime();

}

In Swing, a JButtonclick raises an ActionEvent, which is passed to the ActionListenerconfigured for the button. In Android, a button click causes onClick()to be invoked in the OnClickListenerinstance configured for the button. The listener is provided the view that triggered the click (in this case, the button). All we do here is call that private updateTime()method:

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

Интервал:

Закладка:

Сделать

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

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


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

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

x