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

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

Интервал:

Закладка:

Сделать

For example, here are the lines from the NooYawkactivity’s onCreate()method that accomplish the latter points:

ViewGroup zoom = (ViewGroup) findViewById(R.id.zoom);

zoom. addView(map. getZoomControls());

Then, you can manually get the zoom controls to appear by calling displayZoomControls()on your MapView, or they will automatically appear when the user pans the map as seen in Figure 34-1.

Figure 341 Map with zoom indicator and compass rose Center Typically you - фото 89

Figure 34-1. Map with zoom indicator and compass rose

Center

Typically, you will need to control what the map is showing, beyond the zoom level, such as the user’s current location, or a location saved with some data in your activity. To change the map’s position, call setCenter()on the MapController.

This takes a GeoPointas a parameter. A GeoPointrepresents a location, via latitude and longitude. The catch is that the GeoPointstores latitude and longitude as integers representing the actual latitude and longitude multiplied by 1E6. This saves a bit of memory versus storing a floator double, and it probably speeds up some internal calculations Android needs to do to convert the GeoPointinto a map position. However, it does mean you have to remember to multiply the “real world” latitude and longitude by 1E6.

Rugged Terrain

Just as the Google Maps you use on your full-size computer can display satellite imagery, so too can Android maps.

MapViewoffers toggleSatellite(), which, as the names suggest, toggles on and off the satellite perspective on the area being viewed. You can have the user trigger these via an options menu or, in the case of NooYawk, via keypresses:

@Override

publicboolean onKeyDown(int keyCode, KeyEvent event) {

if(keyCode == KeyEvent.KEYCODE_S) {

map. setSatellite(!map. isSatellite());

return( true);

} else if(keyCode == KeyEvent.KEYCODE_Z) {

map. displayZoomControls( true);

return( true);

}

return( super. onKeyDown(keyCode, event));

}

Layers Upon Layers

If you have ever used the full-size edition of Google Maps, you are probably used to seeing things overlaid atop the map itself, such as “push-pins” indicating businesses near the location being searched. In map parlance — and, for that matter, in many serious graphic editors — the push-pins are on a separate layer than the map itself, and what you are seeing is the composition of the push-pin layer atop the map layer.

Android’s mapping allows you to create layers as well, so you can mark up the maps as you need to based on user input and your application’s purpose. For example, NooYawkuses a layer to show where select buildings are located in the island of Manhattan.

Overlay Classes

Any overlay you want to add to your map needs to be implemented as a subclass of Overlay. There is an ItemizedOverlaysubclass available if you are looking to add push-pins or the like; ItemizedOverlaysimplifies this process.

To attach an overlay class to your map, just call getOverlays()on your MapViewand add()your Overlayinstance to it:

marker. setBounds(0, 0, marker. getIntrinsicWidth(),

marker. getIntrinsicHeight());

map. getOverlays(). add( new SitesOverlay(marker));

We will explain that marker in just a bit.

Drawing the ItemizedOverlay

As the name suggests, ItemizedOverlayallows you to supply a list of points of interest to be displayed on the map — specifically, instances of OverlayItem. The overlay, then, handles much of the drawing logic for you. Here are the minimum steps to make this work:

• First, override ItemizedOverlayOverlayItemas your own subclass (in this example, SitesOverlay)

• In the constructor, build your roster of OverlayIteminstances, and call populate()when they are ready for use by the overlay

• Implement size()to return the number of items to be handled by the overlay

• Override createItem()to return OverlayIteminstances given an index

• When you instantiate your ItemizedOverlaysubclass, provide it with a Drawablethat represents the default icon (e.g., push-pin) to display for each item

The marker from the NooYawkconstructor is the Drawable used for the last bullet — it shows a push-pin, as illustrated in Figure 34-1 earlier in this chapter.

You may also wish to override draw()to do a better job of handling the shadow for your markers. While the map will handle casting a shadow for you, it appears you need to provide a bit of assistance for it to know where the “bottom” of your icon is, so it can draw the shadow appropriately.

For example, here is SitesOverlay:

private classSitesOverlay extendsItemizedOverlay {

privateList items = newArrayList();

privateDrawable marker = null;

public SitesOverlay(Drawable marker) {

super(marker);

this.marker = marker;

items. add( new OverlayItem( getPoint(40.748963847316034,

-73.96807193756104), "UN", "United Nations"));

items. add( new OverlayItem( getPoint(40.76866299974387,

-73.98268461227417), "Lincoln Center",

"Home of Jazz at Lincoln Center"));

items. add( new OverlayItem( getPoint(40.765136435316755,

-73.97989511489868), "Carnegie Hall",

"Where you go with practice, practice, practice"));

items. add( new OverlayItem( getPoint(40.70686417491799,

-74.01572942733765), "The Downtown Club",

"Original home of the Heisman Trophy"));

populate();

}

@Override

protectedOverlayItem createItem(int i) {

return(items. get(i));

}

@Override

publicvoid draw(Canvas canvas, MapView mapView,

boolean shadow) {

super. draw(canvas, mapView, shadow);

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

Интервал:

Закладка:

Сделать

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

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


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

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

x