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

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

Интервал:

Закладка:

Сделать

android:paddingLeft="4px"

android:layout_gravity="center_vertical" />

android:layout_height="80px"

android:background="#884400" />

android:paddingLeft="4px"

android:layout_gravity="center_vertical" />

android:layout_height="80px"

android:background="#aa8844" />

android:paddingLeft="4px"

android:layout_gravity="center_vertical" />

android:layout_height="80px"

android:background="#ffaa88" />

android:paddingLeft="4px"

android:layout_gravity="center_vertical" />

android:layout_height="80px"

android:background="#ffffaa" />

android:paddingLeft="4px"

android:layout_gravity="center_vertical" />

android:layout_height="80px"

android:background="#ffffff" />

android:paddingLeft="4px"

android:layout_gravity="center_vertical" />

Without the ScrollView, the table would take up at least 560 pixels (7 rows at 80 pixels each, based on the Viewdeclarations). There may be some devices with screens capable of showing that much information, but many will be smaller. The ScrollViewlets us keep the table as is, but present only part of it at a time.

On the stock Android emulator, when the activity is first viewed, you see what’s shown in Figure 7-8.

Figure 78 The ScrollViewDemo sample application Notice how only five rows - фото 19

Figure 7-8. The ScrollViewDemo sample application

Notice how only five rows and part of the sixth are visible. By pressing the up/down buttons on the directional pad, you can scroll up and down to see the remaining rows. Also note how the right side of the content gets clipped by the scrollbar — be sure to put some padding on that side or otherwise ensure your own content does not get clipped in that fashion.

CHAPTER 8

Using Selection Widgets

In Chapter 6, you saw how fields could have constraints placed upon them to limit possible input, such as numeric-only or phone-number-only. These sorts of constraints help users “get it right” when entering information, particularly on a mobile device with cramped keyboards.

Of course, the ultimate in constrained input is to select a choice from a set of items, such as the radio buttons seen earlier. Classic UI toolkits have listboxes, comboboxes, drop-down lists, and the like for that very purpose. Android has many of the same sorts of widgets, plus others of particular interest for mobile devices (e.g., the Galleryfor examining saved photos).

Moreover, Android offers a flexible framework for determining what choices are available in these widgets. Specifically, Android offers a framework of data adapters that provide a common interface to selection lists ranging from static arrays to database contents. Selection views — widgets for presenting lists of choices — are handed an adapter to supply the actual choices.

Adapting to the Circumstances

In the abstract, adapters provide a common interface to multiple disparate APIs. More specifically, in Android’s case, adapters provide a common interface to the data model behind a selection-style widget, such as a listbox. This use of Java interfaces is fairly common (e.g., Java/Swing’s model adapters for JTable), and Java is far from the only environment offering this sort of abstraction (e.g., Flex’s XML data-binding framework accepts XML inlined as static data or retrieved from the Internet).

Android’s adapters are responsible for providing the roster of data for a selection widget plus converting individual elements of data into specific views to be displayed inside the selection widget. The latter facet of the adapter system may sound a little odd, but in reality it is not that different from other GUI toolkits’ ways of overriding default display behavior. For example, in Java/Swing, if you want a JList-backed listbox to actually be a checklist (where individual rows are a checkbox plus label, and clicks adjust the state of the checkbox), you inevitably wind up calling setCellRenderer()to supply your own ListCellRenderer, which in turn converts strings for the list into JCheckBox-plus- JLabelcomposite widgets.

Using ArrayAdapter

The easiest adapter to use is ArrayAdapter— all you need to do is wrap one of these around a Java array or java.util.Listinstance, and you have a fully-functioning adapter:

String[] items={this, is, a,

really, silly, list};

newArrayAdapter( this,

android.R.layout.simple_list_item_1, items);

The ArrayAdapterconstructor takes three parameters:

• The Contextto use (typically this will be your activity instance)

• The resource ID of a view to use (such as a built-in system resource ID, as previously shown)

• The actual array or list of items to show

By default, the ArrayAdapterwill invoke toString()on the objects in the list and wrap each of those strings in the view designated by the supplied resource. android.R.layout.simple_list_item_1simply turns those strings into TextViewobjects. Those TextViewwidgets, in turn, will be shown the list or spinner or whatever widget uses this ArrayAdapter.

You can subclass ArrayAdapterand override getView()to “roll your own” views:

publicView getView(int position, View convertView,

ViewGroup parent) {

if(convertView== null) {

convertView = new TextView( this);

}

convertView. setText( buildStringFor(position));

return(convertView);

}

Here, getView()receives three parameters:

• The index of the item in the array to show in the view

• An existing view to update with the data for this position (if one already existed, such as from scrolling — if null, you need to instantiate your own)

• The widget that will contain this view, if needed for instantiating the view

In the previous example, the adapter still returns a TextView, but uses a different behavior for determining the string that goes in the view. Chapter 9 will cover fancier ListViews.

Other Key Adapters

Here are some other adapters in Android that you will likely use:

CursorAdapterconverts a Cursor, typically from a content provider, into something that can be displayed in a selection view

SimpleAdapterconverts data found in XML resources

ActivityAdapterand ActivityIconAdapterprovide you with the names or icons of activities that can be invoked upon a particular intent

Lists of Naughty and Nice

The classic listbox widget in Android is known as ListView. Include one of these in your layout, invoke setAdapter()to supply your data and child views, and attach a listener via setOnItemSelectedListener()to find out when the selection has changed. With that, you have a fully-functioning listbox.

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

Интервал:

Закладка:

Сделать

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

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


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

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

x