Thursday, November 25, 2010

Android wheel update: animation

The wheel widget has been updated. There has been added the main feature - animation.
Now it is possible to scroll the wheel automatically by using the finger fling.
In the same way there is the ability to scroll the wheel programmatically by using next methods:
  • void setCurrentItem(int index, boolean animated) - scrolls to specified items if animated is true
  • void scroll(int itemsToScroll, int time) - scrolls up/down by itemsToScroll items
The main feature that is not implemented at this moment is custom views for wheel items. It will be implemented soon.

Friday, November 19, 2010

Weather forecast widget: Weather providers

The one of main parts of weather forecast widget is communication with weather provider.

I have found next providers (please let me know if you know another ones) that work only with the US cities (except Google weather):

Friday, November 12, 2010

Project for beginners

The main problem for beginners is to choose a project to learn Android. It needs to invent a test app for each topic from Android SDK Developer's Guide. And as a result there are lots projects that in general don't have any value.

It would be better to choose a one project that covers as much as possible items from Android SDK. A one of good project that helps learning Android is the Weather forecast App widget.

There can be covered next items:
  • App Widgets
  • User Interface (layouts, menus, dialogs etc.)
  • Resources (drawables, stings, styles & themes)
  • Intents
  • Content Providers
  • XML and Web servers (weather providers)

Saturday, October 30, 2010

Android wheel update: scrolling

I'm glad to inform that the Android wheel widget has been updated.
Now scrolling feature looks more user friendly and the wheel is updated smoothly, like expected.

I've also renamed methods of the scrolling listener interface to make them clear to understand. They are called now onScrollingStarted() and onScrollingFinished().

The next feature planned to be added is the animation. It is the main feature of Wheel control, and in the same time it is the most difficult to implement. So, it requires some time to be done, and I hope I will have enough time to do that.

BTW, some people try to implement the animation,  moreover, there is an job offer that asks to implement the animation for the money :)
Unfortunately, I'm not able to do that as quick as expected, so they could wait for 1-2 months until I implement that.

Sunday, August 29, 2010

Android wheel update: event listeners

The wheel control has been updated.
There have been added next wheel event listeners:
  • OnWheelChangedListener - onChange() callback is invoked whenever current wheel position is changed
  • OnWheelScrollListener - onScrollStarts() and onScrollEnds() callbacks are invoked when wheel begins/ends being scrolling.

Monday, August 16, 2010

Rounding picture

Suppose we have an image and we would like to make it's corners rounded.
 The main idea is to combine the original image and already prepared rounded image with the same height and width, and use only those pixels from original image that are present at the rounded one:

Monday, July 12, 2010

Android wheel Google code project

I've upload my wheel widget to the Google code and time to time update it.

At this moment I've implemented adapters for wheel view called ArrayWheelAdapter and NumericWheelAdapter. There has been created demo app that contains activities for all these adapters.
The NumericWheelAdapter demos look like in original NumericWheel control (password and date picker activity). And ArrayWheelAdapter is used to set text to wheel items, like next.

I hope this project will be useful for developers.

Updated: You can find my control by Google - it is a one of the top item of  search results.

Tuesday, June 15, 2010

SOAP on Android

Some projects require to communicate with Web services.
The JDK provides tool called wsimport that generates classes from WSDL, and user works with them like with other Java classes and may not know that he works with a Web service.

But it does not work on Android... Android  SDK does not provide classes to work with Web services. So, it needs to manually work with Web services by using SOAP.

There is a good library called kSOAP 2 that is a lightweight SOAP Web service client library for constrained Java environments such as Applets or J2ME applications. There is a port of this library to Android platform that is allowed on Google code.

Wednesday, June 2, 2010

Wheel UI contol: ideas for the future

The wheel control described in previous posts contains all necessary functionality and is ready for using by other applications.
But I would consider it just as a draft for a real wheel view. It needs to "tune" this control to make it more attractive.
Next are some ideas that I'd like to realize:
  1. Implement the animation like in the original iPhone widget
  2. Add the ability to work not only with numbers. Make it to use Adapters like the ListView.
  3. Make the control to be composed. It should contain as much wheels as necessary, so it will allow to avoid defining a set of the wheels for complex widget, like for password and date time picker widgets from the first post about the wheel widget. It can be used by next way:



     // Get the wheel view
     WheelView picker = (WheelView) findViewById(R.id.date_time);
    
     // Add the hours wheel
     WheelViewSection hours = picker.addSection("hours");
     // Set adapter for hours.
     hours.setAdapter(new NumericAdapter(0, 23));
    
     // Add the mins wheel
     WheelViewSection mins = picker.addSection("mins");
     // Set adapter for it
     mins.setAdapter(new NumericAdapter(0, 59));
    
     // Set current values
     Calendar c = Calendar.getInstance();
     mins.setSelectedIndex(c.get(Calendar.MINUTE));
     hours.setSelectedIndex(c.get(Calendar.HOUR_OF_DAY));
    
     // ...
    
     // Get password view
     WheelView passw = (WheelView) findViewById(R.id.passw);
     // Set count of sections
     passw.setSectionCount(4);
     // Set numeric adapter for all sections
     passw.setAdapter(new NumericAdapter(0, 9));
    

  4. Repeat the wheel items when necessary. It means to show the first item after the last one. For example, when user select 59 mins there will be shown the 0 and 1 value below; for hours it can be not used and it can show blank items below the 23 and above the 0 hours.
It's all the ideas that I have at this moment. If you have more ideas please let me know.

See also
    Introduction to the Wheel control
    The Wheel control layouts
    The Wheel control backgrounds
    Scrolling the wheel control


Updated: I've posted sources of the Wheel widget to Google code. Please use this link.


    Friday, May 28, 2010

    Wheel UI contol: Scrolling

    The main feature of the Wheel control is a scrolling (rotation). And I'd like to describe a simple wheel scrolling, without animation.

    The wheel control should be scrolled on touch motion event. So, it needs to override onTouchEvent() method to rotate the wheel. Each time it needs to update the wheel according to motion distance that can be calculated as the difference between the last and current Y motion position.
    In our case we will update the wheel control by setting the current number. If motion distance is less than zero (the movement from bottom to top) we have to increment it, and decrement otherwise. Note that we have to skip that if the movement is so small (is less than one item height).
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            lastYTouch = event.getY();
            break;
    
        case MotionEvent.ACTION_MOVE:
            float delta = event.getY() - lastYTouch;
            int count = (int) (visibleItems * delta / getHeight());
            int pos = currentValue - count;
            pos = Math.max(pos, minValue);
            pos = Math.min(pos, maxValue);
            if (pos != currentValue) {
                lastYTouch = event.getY();
                setValue(pos);
            }
            break;
        case MotionEvent.ACTION_UP:
            break;
        }
        return true;
    }
    
    /**
     * Sets current value
     * 
     * @param value the value to set
     */
    public void setValue(int value) {
        if (value != currentValue && value >= minValue && value <= maxValue) {
            itemsLayout = null;
            valueLayout = null;
            currentValue = value;
            invalidate();
        }
    }
    

    Note that it is just a simple scrolling implementation, and it is not as good as expected. But there is nothing impossible, and I think it can be extended to have the behavior like original iPhone widget.

    See also
        Introduction to the Wheel control
        The Wheel control layouts
        The Wheel control backgrounds
        Ideas for the future

    Thursday, May 27, 2010

    Wheel UI contol: Backgrounds

    The NumericWheel widget has a simple design. It contains only text data (described in previous topic) and gradient backgrounds that are described in this post.

    Backgrounds
    There are used next backgrounds:
    • Main widget background
    • Center (current item) background
    • Top and bottom shadows

    Wednesday, May 26, 2010

    Wheel UI contol: Layouts

    The NumericWheel widget has a simple design. It contains only text data and gradient backgrounds. In this post I'd like to write about text layouts.


    Text layouts
    Widget contains three text fields:
    • Current value - number on middle area  ("11" on image above)
    • Label - text on right area ("hour" on image above)
    • Items - all visible numbers excluding current value ("9", "10", "12", "13" on image above)
    Next picture shows how all these items are "placed" on the widget.

    About the Control area - it is just a space where defined above items are placed. It is the whole widget area excluding left and right padding. Note that there is also indent between Items and the Label areas.

    Tuesday, May 25, 2010

    Wheel UI contol

    Have you ever seen the iPhone date time picker?

    Next is the corresponding Android control

    Poor design...

    But, fortunately, there is an ability to create own UI controls. So I decided to implement this one.


    Tuesday, May 18, 2010

    Creating backgrounds: it's easy (part 3)

    Here is the last topic about creating simple Android backgrounds.

    I had some problems during investigating XML Android drawable because there were missed good docs about that. Definitions in Android API documentation are not full and clear.

    Fortunately, I've found a great doc that describes all XML drawable :) Here it is.
    As you can see Android provides a lot of useful things for defining XML drawable: rotating, animating, scaling, uniting a set of drawable etc.

    Wednesday, May 12, 2010

    Creating backgrounds: it's easy (part 2)

    Here is the first topic about creating simple Android backgrounds.

    What about gradients?


     It's easy - just use gradient XML tag:

    <shape xmlns:android="http://schemas.android.com/apk/res/android">
       
    <gradient
           
    android:startColor="#F000FFFF"
            android:centerColor
    ="#40004444"
            android:endColor
    ="#00000000"
            android:angle
    ="90" />
       
    <corners android:radius="8dp" />
    </shape>

    Friday, April 23, 2010

    Creating backgrounds: it's easy (part 1)

    During developing UI applications for Android, you often have to work with images: icons, backgrounds and others. If you need icon, you (or your designer) paint it using some image editor, like PhotoShop. But what should you do when it needs to create just a simple background for your widget? Install an image editor, research that, and then create background? - Too many actions for creating a simple background.

    Android SDK provides a set of easy ways to define backgrounds, and one of them is the shape drawable XML element. For instance, here is a rounded green drawable:

    <shape xmlns:android="http://schemas.android.com/apk/res/android">
        
    <solid android:color="#FF00FF00"/>
        
    <corners android:radius="8dp" />
    </shape>

    Let create a simple rounded App widget that has an icon and text with a transparent background:


    It changes own view on selecting and pressing, like a lot of Android widgets (icons on Home, buttons etc.):

    State Selected

    State Pressed


    Here is the background drawable of App widget:

    <selector xmlns:android="http://schemas.android.com/apk/res/android">
        
    <item android:state_window_focused="false" android:drawable="@drawable/bg_normal" />
        
    <item android:state_pressed="true" android:drawable="@drawable/bg_pressed" />
        
    <item android:state_focused="true" android:drawable="@drawable/bg_selected" />
        
    <item android:drawable="@drawable/bg_normal" />
    </selector>

    Normal background (bg_normal.xml) has transparent color and rounded corners:

    <shape xmlns:android="http://schemas.android.com/apk/res/android">
        
    <solid android:color="#AA111111"/>
        
    <padding android:left="6dp" android:top="6dp"
             android:right
    ="6dp" android:bottom="6dp" />
        
    <corners android:radius="8dp" />
    </shape>


    Selected (bg_selected.xml) and Pressed (bg_pressed.xml) backgrounds extend Normal background by adding border and changing background color. They look alike, just have different border colors (#FFEEC000 - for pressed, #FFFF8000 - for selected):

    <shape xmlns:android="http://schemas.android.com/apk/res/android">
        
    <solid android:color="#A777"/>
        
    <padding android:left="6dp" android:top="6dp"
             android:right
    ="6dp" android:bottom="6dp" />
        
    <corners android:radius="8dp" />
        
    <stroke android:width="4dip" android:color="#FFFF8000" />
    </shape>

    Wednesday, April 14, 2010

    Android system images (eng)

    HTC provides images of their devices that can be run by the Android emulator.
    Just download necessary system image from HTC developer center page, create a new Android virtual device and put the downloaded image into the created AVD folder. Then start the emulator.

    Next are a few screen shots.



    After you sign in with a Google account, you have access to all of the market apps right from the emulator.

    Friday, April 2, 2010

    Android resources (eng)

    Do you know Android SDK contains all resources used by standard widgets? Icons, animations, styles and so on.
    They are placed on the <Android SDK folder>/data/res folder. And it is possible to use them directly, so it is not necessary to add them into project.


    For example, here is a checked list view that uses starts instead of habitual marks:

    To do that just do next:
    • Define list view item layout (let call it star_checked_item). You can use standard layout for android.R.layout.simple_list_item_checked - layouts/simple_list_item_checked.xml file.
            <CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"
                android:id="@+android:id/text1"
                android:layout_width="fill_parent"
                android:layout_height="?android:attr/listPreferredItemHeight"
                android:textAppearance="?android:attr/textAppearanceLarge"

                android:gravity="center_vertical"
                android:checkMark="@android:drawable/btn_star" <!-- Mark style -->
                android:paddingLeft="6dip"
                android:paddingRight="6dip"/>
    •  Use this layout in list view adapter
             ArrayAdapter adapter = new ArrayAdapter(this, R.layout.star_checked_item); 
             list.setAdapter(adapter);

    Android resources

    Знаете ли вы, что Android SDK содержит ресурсы, которые используются стандартными контролами? Это иконки, анимации, стили, лайауты и пр.
    Все они находится в папке <Android SDK folder>/data/res. При этом, к ним можно обращаться напрямую, то есть нет необходимости добавлять их в свой проект.

    Вот, например, приложение, которое представляет собой checked list view, только использует звездочки вместо привычных галочек для своих элементов:

    Все, что надо для этого - это:
    • Определить лайаут для элеметов списка (назовем его star_checked_item) Можно использовать как шаблон лайаут для android.R.layout.simple_list_item_checked - файл layouts/simple_list_item_checked.xml
            <CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"
                android:id="@+android:id/text1"
                android:layout_width="fill_parent"
                android:layout_height="?android:attr/listPreferredItemHeight"
                android:textAppearance="?android:attr/textAppearanceLarge"
                android:gravity="center_vertical"
                android:checkMark="@android:drawable/btn_star" <!-- Стиль метки -->
                android:paddingLeft="6dip"
                android:paddingRight="6dip"/>
    •  Использовать этот лайаут в адаптере
             ArrayAdapter adapter = new ArrayAdapter(this, R.layout.star_checked_item); 
             list.setAdapter(adapter);

    Wednesday, March 24, 2010

    Android Options menu: Internals (eng)

    Android applications (Activities) can have own menus next types:
    • Options menu - the main menu of application, is displayed when user clicks Menu button
    • Сontext menu - the context menu, is shown when user makes long click on some control
    Сontext menu looks like a simple List view dialog and there is a possibility to change its view by using Android themes. I have been investigated an ability to manage the Options menu view and would like to share results in this post.

    Android Options menu: Internals

    Как и во всех платвормах, приложения (Activity) на Андроиде могут иметь свои собственные меню двух видов:
    • Options menu - главное меню программы, появляется при нажатии клавиши Menu.
    • Сontext menu - контекстное меню, появляется при длительном нажатии на каком-либо элементе управления.
    Сontext menu представляет собой обычный List view диалог и есть возможность менять его вид, используя темы. Я исследовал возможность управление видом Options menu и хочу поделиться в этом посте полученными результатами.

    Tuesday, March 16, 2010

    Android SDK: first impression (eng)

    I have started learning the Android SDK. And I'd like to share my impressions about this technology that is new for me.

    So, what I liked:
    • There is used the Java programming language, although Android does not support established Java standards (SE or ME) - it just uses Java syntax and provides a lot of Java standards classes (streams, threads, collections etc)
    • The familiar development environment (eclipse) with Android plug-in (ADT) that does all routine work automatically. For example, it automatically generates classes from defined .aidl files. There are also built-in widgets (layout) editor, manifest file editor that allows editing it as raw XML data as by clicking to necessary buttons :)
    • Simple, clear for understanding documentation. To start developing something for Android it is enough to read the "Android fundamentals" article on developer.android.com.
    • There are supported all famous platforms: Windows, Linux, Mac OS X. For example, In iPhone I don't like the necessity for developing only on Mac OS.
    • Good Virtual devise with an ability to customize device features. There is a set of SDK tools to monitor/control the device - it is possible to view info about each running process, cause Garbage collector etc.

    What I didn't like:
    • The virtual device is starting too slow. For example, iPhone emulator starts immediately with already loaded operation system. Like the "true" device, the Android starts with black screen of terminal :) The good news is that it is enough to start device at once and after work with it, eclipse connects automatically to this device each time. But not skilled developers often close virtual device window and each time have to wait until it starts :)
    • Virtual device works slowly sometimes
    • Sometimes eclipse don't allow to debug application, and it needs to restart it.
    In general, developing for Android is an interesting and very promising direction.

    Android SDK: first impression

    Недавно начал изучать Андроид. И решил поделиться своими впечатлениями как новичка в этой сфере.

    Итак, что понравилось:
    • Используется язык программирования Java, хотя в Андроиде не поддерживается полностью какой-либо стандарт Java (SE или ME) - просто используется синтаксис этого языка + большая куча классов (стримы, потоки, коллекции)
    • Привычная среда разработки (eclipse) со встроенным плагином для Андроида (ADT),, который делает всю рутинную работу автоматически. Например автоматически генерит классы из aild файлов. Также есть встроенный редактор лайаутов + редактор манифест файла, который позволяет как править этот XML файл руками, так и заполнять его, кликая мышкой по кнопочкам :)
    • Простая и понятная документация. Чтобы начать что-то писать под Андроид достаточно прочитать статью "Android fundamentals" на developer.android.com.
    • Поддерживаются все известные платформы: Windows, Linux, Mac OS X. В программировании под iPhone мне не нравится то, что необходимо писать только под маками.
    • Хороший эмулятор с возможностью настраивать конфигурацию девайса. В дистрибутиве идет набор тулзов для управления девайсом - есть возможность просмотреть инфу по каждому процессу, принудительно вызвать сборщик мусора и пр.

    Что не понравилось:
    • Дефайс стартует довольно-таки долго. iPhone эмулятор например стартует мгновенно, без загрузки системы. Андроид же стартует как полноценный девайс с черного экрана :) Радует то, что достаточно один раз его загрузить и потом просто eclipse к нему все время коннектится. Но по неопытности многие закрывают эмулятор после запуска своего приложения и потом опять ждут пока он загрузится :)
    • Девайс иногда тормозит
    • Eclipse иногда тупит и отказывается дебажить приложение, приходится его перезапускать.
    В общем, тема интересная и довольно перспективная.