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 ArrayAdaptersubclass ( CheckAdapter) in getView()looks to see if convertViewis null. If so, we create a new row by inflating a simple layout (see the following code) and also attach a ViewWrapper(also in the following code). For the row’s RatingBar, we add an anonymous onRatingChanged()listener that looks at the row’s tag ( getTag()) and converts that into an Integer, representing the position within the ArrayAdapterthat this row is displaying. Using that, the checkbox can get the actual RowModelfor the row and update the model based upon the new state of the rating bar. It also updates the text adjacent to the RatingBarwhen checked to match the rating-bar state.

• We always make sure that the RatingBarhas the proper contents and has a tag (via setTag()) pointing to the position in the adapter the row is displaying.

The row layout is very simple: just a RatingBarand a TextViewinside a LinearLayout:

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:orientation="horizontal"

>

android:id="@+id/rate"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:numStars="3"

android:stepSize="1"

android:rating="2" />

android:id="@+id/label"

android:paddingLeft="2px"

android:paddingRight="2px"

android:paddingTop="2px"

android:textSize="40sp"

android:layout_width="fill_parent"

android:layout_height="wrap_content"/>

The ViewWrapperis similarly simple, just extracting the RatingBarand the TextViewout of the row View:

classViewWrapper {

View base;

RatingBar rate = null;

TextView label = null;

ViewWrapper(View base) {

this.base = base;

}

RatingBar getRatingBar() {

if(rate== null) {

rate = (RatingBar)base. findViewById(R.id.rate);

}

return(rate);

}

TextView getLabel() {

if(label== null) {

label = (TextView)base. findViewById(R.id.label);

}

return(label);

}

}

And the result (Figure 9-3) is what you would expect, visually.

Figure 93 The RateListDemo application as initially launched This includes - фото 30

Figure 9-3. The RateListDemo application, as initially launched

This includes the toggled checkboxes turning their words into all caps (Figure 9-4).

Figure 94 The same application showing a toprated word And Checking It - фото 31

Figure 9-4. The same application, showing a top-rated word

…And Checking It Twice

The rating list in the previous section works, but implementing it is very tedious. Worse, much of that tedium would not be reusable except in very limited circumstances. We can do better.

What we’d really like is to be able to create a layout like this:

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"

/>

where, in our code, almost all of the logic that might have referred to a ListViewbefore “just works” with the RateListViewwe put in the layout:

public classRateListViewDemo 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( newArrayAdapterString( 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]);

}

}

Things get a wee bit challenging when you realize that in everything up to this point in this chapter, never were we actually changing the ListViewitself. All our work was with the adapters, overriding getView()and inflating our own rows and whatnot.

So if we want RateListViewto take in any ordinary ListAdapterand “just work,” putting checkboxes on the rows as needed, we are going to need to do some fancy footwork. Specifically, we are going to need to wrap the “raw” ListAdapterin some other ListAdapterthat knows how to put the checkboxes on the rows and track the state of those checkboxes.

First we need to establish the pattern of one ListAdapteraugmenting another. Here is the code for AdapterWrapper, which takes a ListAdapterand delegates all of the interface’s methods to the delegate (from the FancyLists/RateListViewsample project at http://apress.com/):

public classAdapterWrapper implementsListAdapter {

ListAdapter delegate = null;

public AdapterWrapper(ListAdapter delegate) {

this.delegate = delegate;

}

publicint getCount() {

return(delegate. getCount());

}

publicObject getItem(int position) {

return(delegate. getItem(position));

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

Интервал:

Закладка:

Сделать

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

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


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

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

x