2009-11-27

[Android] Create compound controls in Qt and Android

If you are a programmer who is familiar with Qt and is writing Android application at the same time, just like me. You might discover that creating a compound control widget in Android and Qt is a bit different. For example, I would like a compound control widget that shows current time and am/pm label if the user prefers not to use 24-hour format.

In Qt, you might extend a QWidget and attach a derived QLayout to it.

class CompondTimeWidget : public QWidget {
public:
    CompondTimeWidget(QWidget* parent) : QWidget(parent) {
        QHBoxLayout* mainLayout = new QHBoxLayout(this);
        // ...
    }
    // ...
};

The QWidget and QLayout are in the difference class hierarchy and every QWidget needs a layout engine attached to it to layout child widgets defined inside it.

But, in Android, things are a bit different. The View and LinearLayout, for instance, are in the same class inheritance hierarchy. For this task, it's better to be done like this,

public class CompoundTimeWidget extends LinearLayout {
    public CompoundTimeWidget(Context context, AttributeSet attrs) {
        super(context, attrs);

        //
        TextView label = new TextView(context);
        addView(label, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

        // Get the rest of the design from xml file.
        View amPmView = mLayoutInflater.inflate(R.layout.am_pm_widget, this, false);
        addView(amPmView);

        // ...
    }
    // ...
}

I am not very biased towards Qt. Still, it's not natural to say, a widget is a LinearLayout. Which one is better? You tell me.