Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

set text in TextView in Handler bad performance

As Android does not support showing the day for a date, I added a TextView to my layout.

On the DatePicker I put an onDateChangedListener. When the date changes, I determine the day of the week and then set it via a Handler to be sure it is done on the UI thread:

// this is being called when the date changes on the DatePicker
public void onDateChanged(DatePicker view, final int year,
                final int monthOfYear, final int dayOfMonth) {
    String dayOfTheWeek = null;

    // some code here to set the 'dayOfTheWeek' string

    h.sendMessage(h.obtainMessage(0, dayOfTheWeek));
}

final Handler h = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        dayOfWeekTextView.setText((String)msg.obj);
    }
};

My issue: when I scroll through the days in the widget (Android 4.0 UI) it is not smooth! I check what the problem was, and it is not the way I determine what the String should be, it is really the setText() in the Handler. Commenting that part uit and everything is ok. Also setting a hardcoded text there (dayOfWeekTextView.setText("SOMETHING');) gives the same problem. It jitters the DatePicker.

Is setText() really that big of an action? Wunderlist shows the day of the week and there it runs smooth, but I just cannot find out how they do it.

I have only tested it on my HTC One X. Anyone an idea?

Edit:

I found out why it is smooth in Wunderlist! I am using the same as them, a DialogFragment. You can set a title on the dialog and that is what Wunderlist uses instead of a TextView. So I'm going to use that (and looks better too ;) )

So when doing 'getDialog().setTitle(dayOfWeek)' there is no problem. Still the question remains: how come the setText is that slow on the UI thread...?

like image 655
Boy Avatar asked Jan 28 '13 06:01

Boy


2 Answers

The bad performance may be a result of a recalculation of the layout. If the textview width is wrap-content, then every time the text changes, the layout is updated. Try fixing the width of the textview.

like image 50
Michael Avatar answered Oct 24 '22 10:10

Michael


SOLUTION A very sexy and dirty solution would be to create 7 TextViews and toggle the visibility of one of them. Until the day that a week is extended to 8 days, this approach should work with much better performance.


On a separate note, this might be due to the layout params of your textview. You might want to give it some extra space, or, in other words, a layout should not be incurred by setText. Am not sure if that is happening.

like image 28
Sherif elKhatib Avatar answered Oct 24 '22 11:10

Sherif elKhatib