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

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

Интервал:

Закладка:

Сделать

The search activity can have any look you want. In fact, other than watching for queries, a search activity looks, walks, and talks like any other activity in your system.

All the search activity needs to do differently is check the intents supplied to onCreate()(via getIntent()) and onNewIntent()to see if one is a search, and, if so, to do the search and display the results.

For example, let’s look at the Search/Loremsample application (available in the Source Code section of http://apress.com). This starts off as a clone of the list-of-lorem-ipsum-words application that we first built back when showing off the ListViewcontainer in Chapter 8, then with XML resources in Chapter 19. Now we update it to support searching the list of words for ones containing the search string.

The main activity and the search activity share a common layout: a ListViewplus a TextViewshowing the selected entry:

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"

/>

In terms of Java code, most of the guts of the activities are poured into an abstract LoremBaseclass:

abstract public classLoremBase extendsListActivity {

abstractListAdapter makeMeAnAdapter(Intent intent);

private static finalint LOCAL_SEARCH_ID = Menu.FIRST+1;

private static finalint GLOBAL_SEARCH_ID = Menu.FIRST+2;

private static finalint CLOSE_ID = Menu.FIRST+3;

TextView selection;

ArrayList items = newArrayList();

@Override

publicvoid onCreate(Bundle icicle) {

super. onCreate(icicle);

setContentView(R.layout.main);

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

try{

XmlPullParser xpp = getResources(). getXml(R.xml.words);

while(xpp. getEventType()!=XmlPullParser.END_DOCUMENT) {

if(xpp. getEventType()==XmlPullParser.START_TAG) {

if(xpp. getName(). equals("word")) {

items. add(xpp. getAttributeValue(0));

}

}

xpp. next();

}

} catch(Throwable t) {

Toast

. makeText( this, "Request failed: " + t. toString(), 4000). show();

}

setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);

onNewIntent( getIntent());

}

@Override

publicvoid onNewIntent(Intent intent) {

ListAdapter adapter = makeMeAnAdapter(intent);

if(adapter== null) {

finish();

} else{

setListAdapter(adapter);

}

}

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

long id) {

selection. setText(items. get(position). toString());

}

@Override

publicboolean onCreateOptionsMenu(Menu menu) {

menu. add(Menu.NONE, LOCAL_SEARCH_ID, Menu.NONE, "Local Search")

. setIcon(android.R.drawable.ic_search_category_default);

menu. add(Menu.NONE, GLOBAL_SEARCH_ID, Menu.NONE, "Global Search")

. setIcon(R.drawable.search). setAlphabeticShortcut(SearchManager.MENU_KEY);

menu. add(Menu.NONE, CLOSE_ID, Menu.NONE, "Close")

. setIcon(R.drawable.eject). setAlphabeticShortcut('c');

return( super. onCreateOptionsMenu(menu));

}

@Override

publicboolean onOptionsItemSelected(MenuItem item) {

switch(item. getItemId()) {

caseLOCAL_SEARCH_ID:

onSearchRequested();

return( true);

caseGLOBAL_SEARCH_ID:

startSearch( null, false, null, true);

return( true);

caseCLOSE_ID:

finish();

return( true);

}

return( super. onOptionsItemSelected(item));

}

}

This activity takes care of everything related to showing a list of words, even loading the words out of the XML resource. What it does not do is come up with the ListAdapterto put into the ListView— that is delegated to the subclasses.

The main activity — LoremDemo— just uses a ListAdapterfor the whole word list:

packagecom.commonsware.android.search;

importandroid.content.Intent;

importandroid.widget.ArrayAdapter;

importandroid.widget.ListAdapter;

public classLoremDemo extendsLoremBase {

@Override ListAdapter makeMeAnAdapter(Intent intent) {

return( newArrayAdapter( this,

android.R.layout.simple_list_item_1, items));

}

}

The search activity, though, does things a bit differently. First, it inspects the Intentsupplied to the abstract makeMeAnAdapter()method. That Intent comes from either onCreate()or onNewIntent(). If the intent is an ACTION_SEARCH, then we know this is a search. We can get the search query and, in the case of this silly demo, spin through the loaded list of words and find only those containing the search string. That list then gets wrapped in a ListAdapterand returned for display:

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

Интервал:

Закладка:

Сделать

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

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


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

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

x