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

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

Интервал:

Закладка:

Сделать

This approach will not work in every case, though. For example, it may be that you have a ListViewfor which some rows will have one line of text and others will have two. In this case, recycling existing rows becomes tricky, as the layouts may differ significantly. For example, if the row we need to create a Viewfor requires two lines of text, we cannot just use a Viewwith one line of text as is. We either need to tinker with the innards of that View, or ignore it and inflate a new View.

Of course, there are ways to deal with this, such as making the second line of text visible or invisible depending on whether it is needed. And on a phone every millisecond of CPU time is precious, possibly for the user experience, but always for battery life — more CPU utilization means a more quickly drained battery.

That being said, particularly if you are a rookie to Android, focus on getting the functionality right first, then looking to optimize performance on a second pass through your code rather than getting lost in a sea of Views, trying to tackle it all in one shot.

Using the Holder Pattern

Another somewhat expensive operation we do a lot with fancy views is call findViewById(). This dives into our inflated row and pulls out widgets by their assigned identifiers so we can customize the widget contents (e.g., change the text of a TextView, change the icon in an ImageView). Since findViewById()can find widgets anywhere in the tree of children of the row’s root View, this could take a fair number of instructions to execute, particularly if we keep having to re-find widgets we had found once before.

In some GUI toolkits, this problem is avoided by having the composite Views, like our rows, be declared totally in program code (in this case, Java). Then accessing individual widgets is merely a matter of calling a getter or accessing a field. And you can certainly do that with Android, but the code gets rather verbose. We need a way that lets us use the layout XML yet cache our row’s key child widgets so we have to find them only once. That’s where the holder pattern comes into play, in a class we’ll call ViewWrapper.

All Viewobjects have getTag()and setTag()methods. These allow you to associate an arbitrary object with the widget. That holder pattern uses that “tag” to hold an object that, in turn, holds each of the child widgets of interest. By attaching that holder to the row View, every time we use the row, we already have access to the child widgets we care about, without having to call findViewById()again.

So, let’s take a look at one of these holder classes (taken from the FancyLists/ViewWrappersample project at http://apress.com/):

classViewWrapper {

View base;

TextView label = null;

ImageView icon = null;

ViewWrapper(View base) {

this.base = base;

}

TextView getLabel() {

if(label== null) {

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

}

return(label);

}

ImageView getIcon() {

if(icon== null) {

icon = (ImageView)base. findViewById(R.id.icon);

}

return(icon);

}

}

ViewWrappernot only holds onto the child widgets, but also lazy-finds the child widgets. If you create a wrapper and never need a specific child, you never go through the findViewById()operation for it and never have to pay for those CPU cycles.

The holder pattern also allows us to do the following:

• Consolidate all our per-widget type casting in one place, rather than having to cast it everywhere we call findViewById()

• Perhaps track other information about the row, such as state information we are not yet ready to “flush” to the underlying model

Using ViewWrapperis a matter of creating an instance whenever we inflate a row and attaching said instance to the row Viewvia setTag(), as shown in this rewrite of getView():

public classViewWrapperDemo 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( new IconicAdapter( this));

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

}

privateString getModel(int position) {

return(((IconicAdapter) getListAdapter()). getItem(position));

}

publicvoid onListItemClick(ListView parent, View v,

int position, long id) {

selection. setText( getModel(position));

}

classIconicAdapter extendsArrayAdapter {

Activity context;

IconicAdapter(Activity context) {

super(context, R.layout.row, items);

this.context = context;

}

publicView getView(int position, View convertView,

ViewGroup parent) {

View row = convertView;

ViewWrapper wrapper = null;

if(row== null) {

LayoutInflater inflater = context. getLayoutInflater();

row = inflater. inflate(R.layout.row, null);

wrapper = new ViewWrapper(row);

row. setTag(wrapper);

} else{

wrapper = (ViewWrapper)row. getTag();

}

wrapper. getLabel(). setText( getModel(position));

if( getModel(position). length() > 4) {

wrapper. getIcon(). setImageResource(R.drawable.delete);

} else{

wrapper. getIcon(). setImageResource(R.drawable.ok);

}

return(row);

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

Интервал:

Закладка:

Сделать

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

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


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

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

x