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

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

Интервал:

Закладка:

Сделать

}

}

}

Just as we check convertViewto see if it is null in order to create the row Viewsas needed, we also pull out (or create) the corresponding row’s ViewWrapper. Then accessing the child widgets is merely a matter of calling their associated methods on the wrapper.

Making a List…

Lists with pretty icons next to them are all fine and well. But can we create ListViewwidgets whose rows contain interactive child widgets instead of just passive widgets like TextViewand ImageView? For example, could we combine the RatingBarwith text in order to allow people to scroll a list of, say, songs and rate them right inside the list?

There is good news and bad news.

The good news is that interactive widgets in rows work just fine. The bad news is that it is a little tricky, specifically when it comes to taking action when the interactive widget’s state changes (e.g., a value is typed into a field). We need to store that state somewhere, since our RatingBarwidget will be recycled when the ListViewis scrolled. We need to be able to set the RatingBarstate based upon the actual word we are viewing as the RatingBaris recycled, and we need to save the state when it changes so it can be restored when this particular row is scrolled back into view.

What makes this interesting is that, by default, the RatingBarhas absolutely no idea what model in the ArrayAdapterit is looking at. After all, the RatingBaris just a widget, used in a row of a ListView. We need to teach the rows which model they are currently displaying, so when their checkbox is checked they know which model’s state to modify.

So, let’s see how this is done, using the activity in the FancyLists/RateListsample project at http://apress.com/. We’ll use the same basic classes as our previous demo—we’re showing a list of nonsense words, which you can then rate. In addition, words given a top rating will appear in all caps.

public classRateListDemo 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);

ArrayList list = newArrayList();

for(String s : items) {

list. add( new RowModel(s));

}

setListAdapter( new CheckAdapter( this, list));

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

}

privateRowModel getModel(int position) {

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

}

publicvoid onListItemClick(ListView parent, View v,

int position, long id) {

selection. setText( getModel(position). toString());

}

classCheckAdapter extendsArrayAdapter {

Activity context;

CheckAdapter(Activity context, ArrayList list) {

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

this.context = context;

}

publicView getView(int position, View convertView,

ViewGroup parent) {

View row = convertView;

ViewWrapper wrapper;

RatingBar rate;

if(row== null) {

LayoutInflater inflater = context. getLayoutInflater();

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

wrapper = new ViewWrapper(row);

row. setTag(wrapper);

rate = wrapper. getRatingBar();

RatingBar.OnRatingBarChangeListener l =

newRatingBar. OnRatingBarChangeListener() {

publicvoid onRatingChanged(RatingBar ratingBar,

float rating, boolean fromTouch) {

Integer myPosition = (Integer)ratingBar. getTag();

RowModel model = getModel(myPosition);

model.rating = rating;

LinearLayout parent = (LinearLayout)ratingBar. getParent();

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

label. setText(model. toString());

}

};

rate. setOnRatingBarChangeListener(l);

} else{

wrapper = (ViewWrapper)row. getTag();

rate = wrapper. getRatingBar();

}

RowModel model = getModel(position);

wrapper. getLabel(). setText(model. toString());

rate. setTag( new Integer(position));

rate. setRating(model.rating);

return(row);

}

}

classRowModel {

String label;

float rating = 2.0f;

RowModel(String label) {

this.label = label;

}

publicString toString() {

if(rating>=3.0) {

return(label. toUpperCase());

}

return(label);

}

}

}

Here is what is different between our earlier code and this activity and getView()implementation:

• While we are still using String[]items as the list of nonsense words, but rather than pouring that Stringarray straight into an ArrayAdapter, we turn it into a list of RowModelobjects. RowModelis this demo’s poor excuse for a mutable model; it holds the nonsense word plus the current checked state. In a real system, these might be objects populated from a Cursor, and the properties would have more business meaning.

• Utility methods like onListItemClick()had to be updated to reflect the change from a pure String modelto use a RowModel.

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

Интервал:

Закладка:

Сделать

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

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


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

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

x