Touch event handling in Blackberry - events

I try to implement simple touch event handling on Blackberry 9550 emulator, but it doesn't work. Actually, touchEvent never gets called, 'cos no text ever appears in the console. Also, I get an annoying "Full Menu" which appears on touching the screen.
Here's the code:
package mypackage;
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.EventInjector.TouchEvent;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.VirtualKeyboard;
import net.rim.device.api.ui.container.MainScreen;
public class MyScreen extends MainScreen
{
public MyScreen()
{
super(NO_SYSTEM_MENU_ITEMS);
getScreen().getVirtualKeyboard().setVisibility(VirtualKeyboard.HIDE_FORCE);
add(new HandleTouch());
}
class HandleTouch extends Field {
protected void layout(int width, int height) {
setExtent(width, height);
}
public void paint(Graphics graphics) {
graphics.drawBitmap(0, 0, this.getWidth(), this.getHeight(), Bitmap.getBitmapResource("bg.png"), 0, 0);
}
public boolean isFocusable() { return true;}
protected boolean touchEvent(TouchEvent message) {
switch( message.getEvent() ) {
case TouchEvent.CLICK:
System.out.println("----------------------------->CLICK");
return true;
case TouchEvent.DOWN:
System.out.println("----------------------------->DOWN");
return true;
case TouchEvent.MOVE:
System.out.println("----------------------------->MOVE");
return true;
}
System.out.println("PRINT ME SOMETHING IN ANY CASE");
return false;
}
public HandleTouch() {
}
}
}

1). First of all, with this code
protected void layout(int width, int height) {
setExtent(width, height);
}
you are actually setting a VERY large size of the field. This because the BB UI framework passes max available/possible dimentions to layout(int width, int height) so the field should use some part within the passed values. In this specific case the width will be the width of the display (360 px) and the height is the max possible height of the VerticalFieldManager (the one your are adding screen fields to, it is implicitly present in the screen's internals) (1073741823 px). So, finally this may result in a very large Bitmap object that is required with the field in order to be painted and you can get an uncaught error "Bitmap is too large" (I did on Storm 9530).
So, the layout() should use some relatively small values, e.g.:
protected void layout(int width, int height) {
setExtent(Math.min(width, 360), Math.min(height, 480));
}
2).
Actually, touchEvent never gets called
Well, actually it does get called. To see that you should simply touch (versus click). Left button of the mouse simulates clicks (a sequence of TouchEvent.DOWN > TouchEvent.CLICK > TouchEvent.UNCLICK > TouchEvent.UP), right button simulates touches (a sequence of TouchEvent.DOWN > TouchEvent.UP).
3).
Also, I get an annoying "Full Menu" which appears on touching the screen.
This is because your field does not consume TouchEvent.UNCLICK event. For instance, with this code your field will not show the popup:
protected boolean touchEvent(TouchEvent message) {
return true;
}
But, that is a bad solution for the popup. It is better to understand what really causes the popup. If TouchEvent.UNCLICK event is not consumed then BB UI framework calls getContextMenu(int instance) and makeContextMenu(ContextMenu contextMenu, int instance) methods of the field. So in order to disable the popup (which is actually a ContextMenu created by the getContextMenu(int instance) you should override the getContextMenu(int instance) to be smth like this:
public ContextMenu getContextMenu(int instance) {
// just in case check if a context menu is requested
// in order not to disable other types of menu
boolean isContextMenu = (Menu.INSTANCE_CONTEXT == instance);
return isContextMenu ? null : super.getContextMenu(instance);
}
4). Finally I'd recommend to not change native/default behavior of touchEvent(TouchEvent message) method. You can just watch/log it, but don't change (always call its super version). This is because touch events handling is more complicated than it may look at first. It is very easy to get a tricky bug here. I do believe most programmers should not change the native behavior of touchEvent(TouchEvent message) unless they really want to create some custom UI component to work with touch gestures. Normally they just want to react on a click (to behave as a ButtonField), however for that you can simply override navigationClick(int status, int time) or navigationUnclick(int status, int time). The BB UI framework will call those methods when user clicks your field on a touch screen.

I would like to add extra info to Arhimed's answer, since this seems to be a landing page for googling touch events...
My experiences are not to contradict him, but to add possible solutions for future readers. I am using BB OS 5.0. My experiences have been with the Storm simulator, and a Torch device. My app was originally written for OS 4.5, so it might be running in some sort of compatibility mode.
1) As explained in his point 4, a Touch Event gets passed along to a Navigation Click event, if touchEvent(TouchEvent) returns false. If navigationClick(int, int) returns false, this prompts the system to display a ContextMenu.
2) On my system, I could not find a method getContextMenu(int). So I could not test his point 3. I presume this gets added in BB6 or later.
3) I did find getContextMenu() - i.e. it takes no parameters. I tried to override that method to return null.
The strange thing is that this method only gets called after the initial context menu popup is shown! The initial context menu popup (?) gets shown, with a button on it for "Full Menu". When that button is pressed, this method gets called, and can be used to populate the MainMenu that appears. ... strange...
However, it means that overriding that method did not solve my problem.
4) I was unable to get a solution by returning true in touchEvent(TouchEvent). I agree that this would have been bad form (hack), but I have learnt to hack a lot on the BB platform. However, scrolling list fields need to have the touch event passed up, so that the scroll works.
5) Eventually I found something similar to the OP's problem with TouchEvent.UNCLICK. It has taken me 18 months to find the method navigationUnClick(int, int). Similar to my point 1 above, an unhandled UNCLICK becomes a navigationUnClick(int, int) call, which can also lead to the context menu being shown.
So by adding similar logic to both navigationClick(int, int) & navigationUnClick(int, int), I was able to get my lists & touches to interact nicely.
This is just supplemental info, that may add to the accepted anser.

Related

Get EditText data on swipe to next Fragment

I have three fragments in a view pager:
A -> B -> C
I would like to get the strings of my two edittexts in Fragment A on swipe to Fragment B to show them in Fragment B. The edittext data may be changed up until the swipe.
Someone has suggested listening for typing and sending data after each one, but the callbacks I know for that change state EVERY key click (which can be expensive). How do I this without using buttons, since their right next to each other, for a more delightful experience?
You can check the data of the EditText on swipe ; if it's not null, then you can send it to any other fragment using Bundle since you are dealing with fragments
With help from #I. Leonard I found a solution here.
It was deprecated so I used the newer version. I put the below code in my fragment class because I needed access to the data without complicating things. It works like a charm!
On the page listener callback, I suggest, calling an interface for inter-fragment communication to do your actions on your home activity or to call the appropriate fragment that can do the work, from the activity.
// set content to next page on scroll start
vPager = (ViewPager) getActivity().findViewById(R.id.viewpager);
vPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
if (state == ViewPager.SCROLL_STATE_SETTLING) {
// ViewPager is slowing down to settle on a page
if (vPager.getCurrentItem() == 1) {
// The page to be settled on is the second (Preview) page
if (!areFieldsNull(boxOne.getText().toString(), boxTwo.getText().toString()))
// call interface method in view pager activity using interface reference
communicator.preview(boxOne.getText().toString(), boxTwo.getText().toString());
}
}
}
});

How do I handle double click on a GWT web application running on a touch device?

I have built a GWT (2.5) web application that, among other things, uses a DataGrid. I have used addDomHandler to add a DoubleClickEvent to select a row and perform an action, and it works great on the desktop. However, when I run the web application on a touch device, the double click zooms the screen instead. Is there are proper way to handle that? I would prefer to override the default behavior of zooming, but I have no idea where to begin. I suppose a long press might be more appropriate, but I have no idea where to begin with that either.
The code:
_dataGrid.addDomHandler(new DoubleClickHandler() {
#Override
public void onDoubleClick(DoubleClickEvent event) {
// Do something exciting here!
}
}, DoubleClickEvent.getType());
The only idea I have it that stopping the propagation of the DOM event may prevent the default zoom behavior.
Although I'd be curious is it registers as a double-click event at all on a touchscreen device. Would be worth trying just putting the handler on Root and seeing if you can even catch the event.
Also try this: just have your application catch -any- DOM event and simply write the name out somehow. That way you, should find out what event is triggering (might be one for long touch!) and can write a handler for that.
OK, I found a solution, but it's probably pretty unique to my situation. What I did was keep the double click handler and I also implemented a slow double click. In other words, if you select the same row of the DataGrid twice in sequence, no matter how fast you do it, then the application interprets that as a double click. Here is the code:
result.addDomHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
Scheduler.get().scheduleDeferred(new Command() {
public void execute () {
if (result.isDoubleTap()) {
// Do the same thing a a double click.
}
}
});
}});
I had a problem with the click handler being fired before the selection change handler, so I had to defer the processing of the click event with the Scheduler. The "result" is a Composite that contains the DataGrid and some other stuff, and in each "result" I store the last selected item in a private variable. Then in IsDoubleTap() all I do is see if the current selection is the same as the last one:
public boolean isDoubleTap() {
boolean result = false;
String selected = getSelected();
if (_lastSelect != null && selected != null && selected.equals(_lastSelect))
result = true;
_lastSelect = selected;
return result;
}
So effectively if you do a normal double click or a slow double click you get the same action. I'm just glad that while I use this result object many places, it is the only place that I use a double click. And I would REALLY like to have a conversion with the committee that decided overriding standard double click behavior with a touch device was a GOOD thing.

ViewModels and IsolatedStorageSettings

Im working on a MVVM Windows phone app that displays weather info.
When the app loads up it opens MainPage.xaml. It makes a call the the service to get weather info and binds that data to the UI. Both Fahrenheit and Celcius info are returned but only one is displayed.
On the setting page, the user can select to view the temp in either Fahrenheit or Celcius.
The user can change this setting at any time and its stored in IsolatedStorageSettings.
The issue Im having is this:
when the user navigates to the Settings page and changes their preference for either Fahrenheit or Celcius, this change is not reflected on the main page.
This issue started me thinking about this in a broader context. I can see this being an issue in ANY MVVM app where the display depends on some setting in IsolatedStorage. Any time any setting in the IsoStore is updated, how does the ViewModels know this? When I navigate back in the NavigationStack from the settings page back to MainPage how can I force a rebind of the page?
The data in my model hasnt changed, only the data that I want to display has changed.
Am I missing something simple here?
Thanks in advance.
Alex
Probably you have code like this:
public double DisplayTemperature
{
get { return (IsCelsium) ? Celsium : Fahrenheit; }
}
And IsCelsium is:
public double IsCelsium
{
get { return (bool)settings["IsCelsium"]; }
set { settings["IsCelsium"] = value; }
}
So you need to add NotifyPropertyChanged event to notify UI to get new values from DisplayTemperature property:
public double IsCelsium
{
get { return (bool)settings["IsCelsium"]; }
set
{
settings["IsCelsium"] = value;
NotifyPropertyChanged("DisplayTemperature");
}
}
Take a look at Caliburn Micro. You could implement something similar or use CM itself. When using CM I don't even think about this stuff, CM makes it so simple.
When your ViewModel inherits from Screen there are life-cycle events that fire that you can override. For example, OnInitialize fires the very first time the ViewModel is Activated and OnActivate fires every time the VM is activated. There's also OnViewAttached and OnViewLoaded.
These methods are the perfect place to put logic to populate or re-populate data.
CM also has some special built in features for allowing one to easily tombstone a single property or an entire object graph into Iso or phone state.
ok, so Ive come up with a solution. Before I get to it, let me provide some background. The app that Im working on uses both MVVM Light and WP7Contrib. That being the case, I am using Funq for DI and the MVVMLight Toolkit. After I posted my initial question, I gave the question a bit more thought. I remembered a video that I watched a while back from MIX2011 called Deep Dive MVVM with Laurent Bugnion
http://channel9.msdn.com/Events/MIX/MIX11/OPN03
In it, he talks about just this problem (view models not living at the same time) on Windows Phone. The part in question starts around the 19 minute mark.
Anyway, after I remembered that and realized that the ViewModel locator is exposed in App.xaml, this became a trivial problem to solve. When the user changes the Fahrenheit/Celcius option on the setting page, I simply get a reference to the MainViewModel via the ViewModelLocator and reset the collection that is bound to the UI thus causing the bindings to update.
public bool AddOrUpdateValue(string Key, Object value)
{
bool valueChanged = false;
// If the key exists
if (settings.Contains(Key))
{
// If the value has changed
if (settings[Key] != value)
{
// Store the new value
settings[Key] = value;
valueChanged = true;
}
}
// Otherwise create the key.
else
{
settings.Add(Key, value);
valueChanged = true;
}
return valueChanged;
}
public bool ImperialSetting
{
get
{
return GetValueOrDefault<bool>(ImperialSettingKeyName, ImperialSettingDefault);
}
set
{
if (AddOrUpdateValue(ImperialSettingKeyName, value))
{
Save();
RaisePropertyChanged("ImperialSettingText");
var vml = new ViewModelLocator();
vml.MainViewModel.Cities = (App.Current as App).Cities;
}
}
}
It was a mistake on my part not to realize that I could get access to the viewModel via the ViewModelLocator. Hopefully this post saves someone else the time I burned on this issue.

QWidget focusOutEvent not received

I've created a date input by subclassing a QLineEdit and a QCalendar. The calender is displayed at the bottom of the QLineEdit when a mousePressEvent is received on it. The problem is with hiding that calendar. I've overridden its focusOutEvent as I want it to be closed when the user clicks somewhere else. But this event is not received at all, I confirmed this by putting a breakpoint in it, it never stops there. I've put a call to close() in it:
class MyCalendarWidget : public QCalendarWidget
{
Q_OBJECT
public:
void focusOutEvent(QFocusEvent* e)
{
close();
}
};
When I close it from my DateLineEdit, it works as expected:
void DateLineEdit::mousePressEvent(QMouseEvent *)
{
if (calendar->isVisible())
{
calendar->close();
}
else
{
calendar->move(mapToGlobal(QPoint(0, height())));
calendar->show();
}
}
I'm guessing it's not sending a focusOutEvent because it never had focus in the first place; certainly not if the user subsequently typed something in the DateLineEdit. Capture the focusOutEvent from the DateLineEdit object, and close the calendar at that point; though perhaps you would want to test whether the user clicked on the calendar (in which case it would have focus or at least have received a mousePressEvent) and leave it up in that case (but otherwise close it).
Are you aware that there is already such thing in Qt? See the setCalendarPopup() & setCalendarWidget() of the QDateTimeEdit class. The only difference I can thing of now is that to see the calendar the user will have to click on the right side of the widget, instead of the editing line.
Hope this helps

How to construct simple wxWidgets image display

I wrote a wxPython program that I am translating to wxWidgets. The program has a scrolled window that displays an image. Following Rappin, wxPython In Action (Listing 12.1), I used a StaticBitmap within a panel. While surfing the latest wxWidgets documentation, I found a dire warning that wxStaticBitmap should only be used for very small images. It says, "... you should use your own control if you want to display larger images portably." Okay. Show me. I don't have my "own control."
Was Rappin wrong, or is the documentation out of date?
The question - a newbie one, no doubt - is what is the right way to do a simple image-view window in wxWidgets? A drop-in replacement for wxStaticBitmap would be nice. I looked into the "image" program in the wxWidgets "samples" directory. It's as long a War and Peace. Surely there must be a canned class or a simple recipe.
Don't let the size of the "image" sample fool you, only a few lines of code are necessary to do what you want.
Search for the MyImageFrame class in the image.cpp file, it is nothing more than a class with a private bitmap field, a custom constructor to set the bitmap and the window client size, and an event handler for EVT_PAINT:
void OnPaint(wxPaintEvent& WXUNUSED(event))
{
wxPaintDC dc( this );
dc.DrawBitmap( m_bitmap, 0, 0, true /* use mask */ );
}
Since you don't want a frame class here's your recipe: You create a simple descendant of wxWindow that has a similar constructor, paint handler and duplicates the methods of wxStaticBitmap that you use in your code. Maybe simply one method to set a new bitmap and resize the control to the new bitmap dimensions.
// A scrolled window for showing an image.
class PictureFrame: public wxScrolledWindow
{
public:
PictureFrame()
: wxScrolledWindow()
, bitmap(0,0)
{;}
void Create(wxWindow *parent, wxWindowID id = -1)
{
wxScrolledWindow::Create(parent, id);
}
void LoadImage(wxImage &image) {
bitmap = wxBitmap(image);
SetVirtualSize(bitmap.GetWidth(), bitmap.GetHeight());
wxClientDC dc(this);
PrepareDC(dc);
dc.DrawBitmap(bitmap, 0, 0);
}
protected:
wxBitmap bitmap;
void OnMouse(wxMouseEvent &event) {
int xx,yy;
CalcUnscrolledPosition(event.GetX(), event.GetY(), &xx, &yy);
event.m_x = xx; event.m_y = yy;
event.ResumePropagation(1); // Pass along mouse events (e.g. to parent)
event.Skip();
}
void OnPaint(wxPaintEvent &event) {
wxPaintDC dc(this);
PrepareDC(dc);
dc.DrawBitmap(bitmap, 0,0, true);
}
private:
DECLARE_EVENT_TABLE()
};
BEGIN_EVENT_TABLE(PictureFrame,wxScrolledWindow)
EVT_PAINT(PictureFrame::OnPaint)
EVT_MOUSE_EVENTS(PictureFrame::OnMouse)
END_EVENT_TABLE()

Resources