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

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

Интервал:

Закладка:

Сделать

However, if your activity is dominated by a single list, you might well consider creating your activity as a subclass of ListActivity, rather than the regular Activitybase class. If your main view is just the list, you do not even need to supply a layout — ListActivitywill construct a full-screen list for you. If you do want to customize the layout, you can, so long as you identify your ListViewas @android:id/list, so ListActivityknows which widget is the main list for the activity.

For example, here is a layout pulled from the Selection/Listsample project. This sample along with all others in this chapter can be found in the Source Code area of http://apress.com.

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

android:orientation="vertical"

android:layout_width="fill_parent"

android:layout_height="fill_parent">

android:id="@+id/selection"

android:layout_width="fill_parent"

android:layout_height="wrap_content"/>

android:id="@android:id/list"

android:layout_width="fill_parent"

android:layout_height="fill_parent"

android:drawSelectorOnTop="false"

/>

It is just a list with a label on top to show the current selection.

The Java code to configure the list and connect the list with the label is:

public classListViewDemo extendsListActivity {

TextView selection;

String[] items={"lorem", "ipsum", "dolor", "sit", "amet",

"consectetuer", "adipiscing", "elit", "morbi", "vel",

"ligula", "vitae", "arcu", "aliquet", "mollis",

"etiam", "vel", "erat", "placerat", "ante",

"porttitor", "sodales", "pellentesque", "augue", "purus"};

@Override

publicvoid onCreate(Bundle icicle) {

super. onCreate(icicle);

setContentView(R.layout.main);

setListAdapter( newArrayAdapter( this,

android.R.layout.simple_list_item_1,

items));

selection=(TextView) findViewById(R.id.selection);

}

publicvoid onListItemClick(ListView parent, View v, int position,

long id) {

selection. setText(items[position]);

}

}

With ListActivity, you can set the list adapter via setListAdapter()— in this case, providing an ArrayAdapterwrapping an array of nonsense strings. To find out when the list selection changes, override onListItemClick()and take appropriate steps based on the supplied child view and position (in this case, updating the label with the text for that position).

The results are shown in Figure 8-1.

Figure 81 The ListViewDemo sample application Spin Control In Android the - фото 20

Figure 8-1. The ListViewDemo sample application

Spin Control

In Android, the Spinneris the equivalent of the drop-down selector you might find in other toolkits (e.g., JComboBoxin Java/Swing). Pressing the center button on the D-pad pops up a selection dialog for the user to choose an item from. You basically get the ability to select from a list without taking up all the screen space of a ListView, at the cost of an extra click or screen tap to make a change.

As with ListView, you provide the adapter for data and child views via setAdapter()and hook in a listener object for selections via setOnItemSelectedListener().

If you want to tailor the view used when displaying the drop-down perspective, you need to configure the adapter, not the Spinnerwidget. Use the setDropDownViewResource()method to supply the resource ID of the view to use.

For example, culled from the Selection/Spinnersample project, here is an XML layout for a simple view with a Spinner:

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

android:orientation="vertical"

android:layout_width="fill_parent"

android:layout_height="fill_parent">

android:id="@+id/selection"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

/>

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:drawSelectorOnTop="true"

/>

This is the same view as shown in the previous section, just with a Spinnerinstead of a ListView. The Spinnerproperty android:drawSelectorOnTopcontrols whether the arrows are drawn on the selector button on the right side of the SpinnerUI.

To populate and use the Spinner, we need some Java code:

public classSpinnerDemo extendsActivity

implementsAdapterView.OnItemSelectedListener {

TextView selection;

String[] items={"lorem", "ipsum", "dolor", "sit", "amet",

"consectetuer", "adipiscing", "elit", "morbi", "vel",

"ligula", "vitae", "arcu", "aliquet", "mollis",

"etiam", "vel", "erat", "placerat", "ante",

"porttitor", "sodales", "pellentesque", "augue", "purus"};

@Override

publicvoid onCreate(Bundle icicle) {

super. onCreate(icicle);

setContentView(R.layout.main);

selection = (TextView) findViewById(R.id.selection);

Spinner spin = (Spinner) findViewById(R.id.spinner);

spin. setOnItemSelectedListener( this);

ArrayAdapter aa = newArrayAdapter( this,

android.R.layout.simple_spinner_item, items);

aa. setDropDownViewResource(

android.R.layout.simple_spinner_dropdown_item);

spin. setAdapter(aa);

}

publicvoid onItemSelected(AdapterView parent,

View v, int position, long id) {

selection. setText(items[position]);

}

publicvoid onNothingSelected(AdapterView parent) {

selection. setText("");

}

}

Here, we attach the activity itself as the selection listener ( spin.setOnItemSelectedListener(this)). This works because the activity implements the OnItemSelectedListenerinterface. We configure the adapter not only with the list of fake words, but also with a specific resource to use for the drop-down view (via aa.setDropDownViewResource()). Also note the use of android.R.layout.simple_spinner_itemas the built-in View for showing items in the spinner itself. Finally, we implement the callbacks required by OnItemSelectedListenerto adjust the selection label based on user input.

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

Интервал:

Закладка:

Сделать

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

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


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

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

x