detect a screen touch outside the spinnersearch view - xamarin.android

i have created an android app via xamarin.android. i have a multispinnersearch in a fragment and when opened normally, all the items inside it are preselected. but i had a problem. if the user touches the screen outside the spinner, the latter closes and all the items get into my list. i don't want that. unless he clicks "ok" in the spinner, no items should be taken to my list. so i tried to handle the touch event to prevent the selection of items on screen touch but it didn't work. here are the codes i tried:
public override bool DispatchTouchEvent(MotionEvent ev)
{
if (ev.Action == MotionEventActions.Down)
{
View v = CurrentFocus;
if (v is MultiSpinnerSearch)
{
Rect outRect = new Rect();
v.GetGlobalVisibleRect(outRect);
if (!outRect.Contains((int)ev.RawX, (int) ev.RawY))
{
Toast.MakeText(this, "shgsg", ToastLength.Long).Show();
}
}
}
return base.DispatchTouchEvent(ev);
}
i tried this in my main activity but i didn't work. then i tried this in my fragment on the ontouch listener interface:
if (e.Action == MotionEventActions.Down)
{
if (labors_dropdown.IsFocused == true)
{
Android.Graphics.Rect rect = new Rect();
labors_dropdown.GetGlobalVisibleRect(rect);
if (!rect.Contains((int)e.RawX, (int)e.RawY))
{
Toast.MakeText(this.Context, "gfgf", ToastLength.Short).Show();
}
}
}
it didn't work too, what should i do? thanks in advance.

You could try the below method:
public override bool DispatchTouchEvent(MotionEvent ev)
{
if (ev.Action == MotionEventActions.Down)
{
View v = (MultiSpinnerSearch)FindViewById<MultiSpinnerSearch>(Resource.Id.xxxxx);
if (!IsTouchPointInView(v, (int)ev.GetX(), (int)ev.GetY()))
{
Toast.MakeText(this, "shgsg", ToastLength.Long).Show();
}
}
return base.DispatchTouchEvent(ev);
}
private bool IsTouchPointInView(View targetView, int currentX, int currentY)
{
if (targetView == null)
{
return false;
}
int[] localtion = new int[2];
targetView.GetLocationOnScreen(localtion);
int left = localtion[0];
int top = localtion[1];
int right = left + targetView.MeasuredWidth;
int bottom = top + targetView.MeasuredHeight;
if (currentY >= top && currentY <= bottom && currentX >= left
&& currentX <= right)
{
return true;
}
return false;
}

Related

Launch macOS shortkeys in Processing on visual button

In Processing, I'm building a simple buttons interface. And the idea is that when you click on a button in the sketch. A text snippet from a different macOS application will launch a text snippet box.
At the moment, this text snippet box will be launched if I type a word in an email. So let's say I type (sample-a) in the email, and this will open a text snippet box that I have set up with this application.
But I want to trigger (sample-a) on a button click in Processing and not have to type this word in the email.
I searched the internet and looked at io.popen, os.execute and launch. But I wondered what the best way is to trigger a macOS "word" from Processing on a button click? Maybe do something with an echo command?
I hope someone can give me some tips or have an example code to create this function?
*added updated code:
// Import library for textfields
import g4p_controls.*;
GTextField txf1;
String sample;
boolean background = true;
// Button setup
final int btnX = 100;
final int btnY = 100;
final int btnW = 200;
final int btnH = 200;
public void setup() {
size(400, 600);
background(209, 209, 209);
// Button
rect(btnX, btnY, btnW, btnH);
// Textfield setup
txf1 = new GTextField(this, 100, 400, 200, 20);
}
public void draw() {
if (keyPressed && key == ENTER) {
}
}
public void handleTextEvents(GEditableTextControl textcontrol, GEvent event) {
if (txf1 == textcontrol && event == GEvent.ENTERED) {
sample = txf1.getText();
}
}
// Button trigger
void mousePressed() {
if (mouseX >= btnX && mouseX <= btnX + btnW && mouseY >= btnY && mouseY <= btnY + btnH) {
println("button clicked");
exec("open", "/Applications/TextExpander.app");
txf1.setText("sample");
}
}
New code for button interface with ControlP5 and Robot Class
import controlP5.*;
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
boolean background = true;
// Robot function
Robot robot;
String keyString="template-1";
Robot1 robot1;
String keyString="template-2";
ControlP5 gui;
void setup() {
size(1440, 900);
gui = new ControlP5(this);
//Add a Button
gui.addButton("Template 1")
.setPosition(50, 50)
.setSize(100, 100)
.setValue(0)
.activateBy(ControlP5.RELEASE);
;
gui.addButton("Template 2")
.setPosition(200, 50)
.setSize(100, 100)
.setValue(0)
.activateBy(ControlP5.RELEASE);
;
// Robot function
try {
robot = new Robot();
robot1 = new Robot1();
}
catch (AWTException ex) {
System.out.println(ex.getMessage());
}
frameRate(1);
// Robot function
}
public void Template1(int value) {
println("Template 1 Button pressed");
sendKeys(robot, keyString);
}
public void Template2(int value) {
println("Template 2 Button pressed");
sendKeys(robot1, keyString);
}
public void controlEvent(ControlEvent theEvent) {
}
// Robot function for Template 1
void sendKeys(Robot robot, String keys) {
for (char c : keys.toCharArray()) {
int keyCode = KeyEvent.getExtendedKeyCodeForChar(c);
if (KeyEvent.CHAR_UNDEFINED == keyCode) {
throw new RuntimeException(
"Key code not found for character '" + c + "'");
}
robot.keyPress(keyCode);
robot.delay(100);
robot.keyRelease(keyCode);
robot.delay(100);
noLoop();
}
}
// Robot function for Template 2
void sendKeys(Robot1 robot1, String keys) {
for (char c : keys.toCharArray()) {
int keyCode = KeyEvent.getExtendedKeyCodeForChar(c);
if (KeyEvent.CHAR_UNDEFINED == keyCode) {
throw new RuntimeException(
"Key code not found for character '" + c + "'");
}
robot1.keyPress(keyCode);
robot1.delay(100);
robot1.keyRelease(keyCode);
robot1.delay(100);
noLoop();
}
}
void draw() {
}
Here is your source code as posted in the comments:
boolean background = true;
void setup() {
size(400, 400);
}
void draw() {
rect(100, 100, 200, 200);
}
boolean isMouseOver(int x, int y, int w, int h) {
if (mouseX >= x && mouseX <= x + w && mouseY >= y && mouseY <= y + h) {
return true;
}
return false;
}
void mousePressed() {
// if (isMouseOver(width/2, height/2, 100, 100) == true){
if (isMouseOver(100, 100, 200, 200) == true) {
println("button clicked");
// Process proc = I'm doing more research on this exec("open", "/Applications/TextExpander.app");
// name of the TextExpander abbreviation / shortcut = "(sample-a)"
// code that fire the word "(sample-a)" so that a TextExpander snippet will popup
}
}
As written there is a problem with mousePressed(); it will only pick up a button click toward the bottom of the button. Clicks at the top do nothing. That's due to an error in the line if(isMouseOver()== true) because the parameters are incorrect; they should be the same as the parameters that you used to create the rect initially, ie (100,100,200,200).
Alternate revision which shortens the code by obviating the function isMouseOver(). Rectangle coordinates are made constants so that if you want to change the size of the button later you only will have to change the parameter once instead of finding multiple occurrences in your code. Your initial version will certainly work as is, but I am only showing you a possible way to improve it. As you continue to experiment we can edit this post to reflect changes. Keep on experimenting and you should hopefully achieve your goal.
boolean background = true;
final int btnX = 100;
final int btnY = 100;
final int btnW = 200;
final int btnH = 200;
void setup() {
size(400, 400);
rect(btnX, btnY, btnW, btnH);
}
void draw() {
}
void mousePressed() {
if (mouseX >= btnX && mouseX <= btnX + btnW && mouseY >= btnY && mouseY <= btnY + btnH) {
println("button clicked");
// Process proc = I'm doing more research on this exec("open", "/Applications/TextExpander.app");
// name of the TextExpander abbreviation / shortcut = "(sample-a)"
// code that fire the word "(sample-a)" so that a TextExpander snippet will popup
}
}
Robot revision:
You don't need two robots; one will suffice. Likewise you don't need two sendKeys() function. Use one robot and send it a different string depending on which button is pressed. Whatever name is used for the button, that string is also used to called a corresponding function and the two must match precisely. That is, if you title the button 'template_1' then the function needs to be 'template_1()' also.
import controlP5.*;
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
Robot robot;
ControlP5 gui;
String keyString = "template-1";
String keyString2 = "template-2";
void setup() {
size(350, 250);
gui = new ControlP5(this);
// Function that's called must match the button title.
gui.addButton("Template_1")
.setPosition(50, 50)
.setSize(100, 100)
.activateBy(ControlP5.RELEASE);
;
gui.addButton("Template_2")
.setPosition(200, 50)
.setSize(100, 100)
.activateBy(ControlP5.RELEASE);
;
try {
robot = new Robot();
} catch (AWTException ex) {
System.out.println(ex.getMessage());
}
}
void Template_1() {
println("Template 1 Button pressed");
sendKeys(keyString);
}
void Template_2() {
println("Template 2 Button pressed");
sendKeys(keyString2);
}
public void controlEvent(ControlEvent evnt) {
println(evnt);
}
void sendKeys(String keys) {
println("sendKeys fired.");
delay(3000); // Give user some time to set cursor
for (char c : keys.toCharArray()) {
println(c);
int keyCode = KeyEvent.getExtendedKeyCodeForChar(c);
if (KeyEvent.CHAR_UNDEFINED == keyCode) {
throw new RuntimeException(
"Key code not found for character '" + c + "'");
}
robot.keyPress(keyCode);
robot.delay(100);
robot.keyRelease(keyCode);
robot.delay(100);
}
}
void draw() {
}

When we try to ZoomIn and ZoomOut on Xamarin Android, several color shades are occur Android version 7 and 8 only

In cameraPageRenderer, we handle zoomIn and zoomOut in our application. When we try to ZoomIn and ZoomOut, several colour shades occur. Please take a look at this image. As a result, we are resolving this issue by handling PrepareAndStartCamera (). Please see the code snippet below.
public override bool OnTouchEvent(MotionEvent e)
{
switch (e.Action & MotionEventActions.Mask)
{
case MotionEventActions.Down:
oldDist = getFingerSpacing(e);
break;
case MotionEventActions.Move:
float newDist = getFingerSpacing(e);
if (newDist > oldDist)
{
//mCamera is your Camera which used to take picture, it should already exit in your custom Camera
handleZoom(true, camera);
}
else if (newDist < oldDist)
{
handleZoom(false, camera);
}
oldDist = newDist;
break;
}
return true;
}
private static float getFingerSpacing(MotionEvent e)
{
if (e.PointerCount == 2)
{
float x = e.GetX(0) - e.GetX(1);
float y = e.GetY(0) - e.GetY(1);
return (float)Math.Sqrt(x * x + y * y);
}
return 0;
}
private void handleZoom(bool isZoomIn, global::Android.Hardware.Camera camera)
{
//camera.StopPreview();
// camera.Release();
// camera = global::Android.Hardware.Camera.Open((int)cameraType);
global::Android.Hardware.Camera.Parameters parameters = camera.GetParameters();
if (parameters.IsZoomSupported)
{
int maxZoom = parameters.MaxZoom;
int zoom = parameters.Zoom;
if (isZoomIn && zoom < maxZoom)
{
zoom++;
}
else if (zoom > 0)
{
zoom--;
}
parameters.Zoom = zoom;
camera.SetParameters(parameters);
camera.SetPreviewTexture(surfaceTexture);
// PrepareAndStartCamera();
}
else
{
Android.Util.Log.Error("lv", "zoom not supported");
}
}
After using PrepareAndStartCamera(), when ZoomingIn or ZoomingOut the camera and taking a picture, it returns to the normal size picture. if we are not using this PrepareAndStartCamera() method, then the Color shades are appear.
private void PrepareAndStartCamera()
{
try
{
camera.StopPreview();
var display = activity.WindowManager.DefaultDisplay;
if (display.Rotation == SurfaceOrientation.Rotation0)
{
camera.SetDisplayOrientation(90);
}
if (display.Rotation == SurfaceOrientation.Rotation270)
{
camera.SetDisplayOrientation(180);
}
camera.StartPreview();
}
}

Unity - Disable AR HitTest after initial placement

I am using ARKit plugin for Unity leveraging the UnityARHitTestExample.cs.
After I place my object into the world scene I want to disable the ARKit from trying to place the object again every time I touch the screen. Can someone please help?
There are a number of ways you can achieve this, although perhaps the simplest is creating a boolean to determine whether or not your model has been placed.
First off all you would create a boolean as noted above e.g:
private bool modelPlaced = false;
Then you would set this to true within the HitTestResultType function once your model has been placed:
bool HitTestWithResultType (ARPoint point, ARHitTestResultType resultTypes)
{
List<ARHitTestResult> hitResults = UnityARSessionNativeInterface.GetARSessionNativeInterface ().HitTest (point, resultTypes);
if (hitResults.Count > 0) {
foreach (var hitResult in hitResults) {
//1. If Our Model Hasnt Been Placed Then Set Its Transform From The HitTest WorldTransform
if (!modelPlaced){
m_HitTransform.position = UnityARMatrixOps.GetPosition (hitResult.worldTransform);
m_HitTransform.rotation = UnityARMatrixOps.GetRotation (hitResult.worldTransform);
Debug.Log (string.Format ("x:{0:0.######} y:{1:0.######} z:{2:0.######}", m_HitTransform.position.x, m_HitTransform.position.y, m_HitTransform.position.z));
//2. Prevent Our Model From Being Positioned Again
modelPlaced = true;
}
return true;
}
}
return false;
}
And then in the Update() function:
void Update () {
//Only Run The HitTest If We Havent Placed Our Model
if (!modelPlaced){
if (Input.touchCount > 0 && m_HitTransform != null)
{
var touch = Input.GetTouch(0);
if (touch.phase == TouchPhase.Began || touch.phase == TouchPhase.Moved)
{
var screenPosition = Camera.main.ScreenToViewportPoint(touch.position);
ARPoint point = new ARPoint {
x = screenPosition.x,
y = screenPosition.y
};
ARHitTestResultType[] resultTypes = {
ARHitTestResultType.ARHitTestResultTypeExistingPlaneUsingExtent,
};
foreach (ARHitTestResultType resultType in resultTypes)
{
if (HitTestWithResultType (point, resultType))
{
return;
}
}
}
}
}
}
Hope it helps...

XF how to lock focus on entry in iOS?

I have some entries in my app which contain some numbers and I have a button that when I click on the button it adds one unit to the number in the entry that is focused, but the problem is that when i click the button, the entry loses the focus and keyboard disappears, although I want the entry to be focused, I found a solution for Android, but couldn't find anything for iOS!!
Does anybody know what to do? I don't want the entry to lose focus
Update:
private void StepUpButton_Clicked(object sender, EventArgs e)
{
double value;
for (int i = 0; i < 30; i++)
{
if (GetEntries(i).IsFocused)
{
if (String.IsNullOrEmpty(GetEntries(i).Text) || GetEntries(i).Text.Equals("-"))
{
value = 0.00;
}
else
{
value = Convert.ToDouble(GetEntries(i).Text);
}
for (int j = 0; j < 10; j++)
{
if (GetEntries(i) == GetVa1ToVb1Amp(j))
{
GetVa1ToVb1Amp(j).Text = controller.StepUpClicked(0, value).ToString("F2");
}
if (GetEntries(i) == GetIa1ToIb3Amp(j))
{
GetIa1ToIb3Amp(j).Text = controller.StepUpClicked(1, value).ToString("F3");
}
if (GetEntries(i) == GetVa1ToIb3Phase(j))
{
GetVa1ToIb3Phase(j).Text = controller.StepUpClicked(2, value).ToString("F2");
}
if (GetEntries(i) == GetVa1ToIb3Freq(j))
{
GetVa1ToIb3Freq(j).Text = controller.StepUpClicked(3, value).ToString("F3");
}
}
}
}
}

How to add text input field in cocos2d.Android cocos sharp?

I am trying to get CCTextFieldTTF to work in cocos sharp with Xamarin for an android application. But can't get hold of this for the life of me. Could not find any documentation on cocos sharp API either. Does anyone know how to use this class to render a text area in an android application? The reason I am asking is in a xamarin forum I saw someone saying that this does not work in the API yet. Any help would be highly appreciated. Thanks in advance.
I have this working in android
Here is the sample code:
Create a node to track the textfield
CCTextField trackNode;
protected CCTextField TrackNode
{
get { return trackNode; }
set
{
if (value == null)
{
if (trackNode != null)
{
DetachListeners();
trackNode = value;
return;
}
}
if (trackNode != value)
{
DetachListeners();
}
trackNode = value;
AttachListeners();
}
}
//create the actual input textfield
var textField = new CCTextField(string.Empty, "Somefont", 25, CCLabelFormat.SystemFont);
textField.IsColorModifiedByOpacity = false;
textField.Color = new CCColor3B(Theme.TextWhite);
textField.BeginEditing += OnBeginEditing;
textField.EndEditing += OnEndEditing;
textField.Position = new CCPoint (0, 0);
textField.Dimensions = new CCSize(VisibleBoundsWorldspace.Size.Width - (160 * sx), vPadding);
textField.PlaceHolderTextColor = Theme.TextYellow;
textField.PlaceHolderText = Constants.TextHighScoreEnterNamePlaceholder;
textField.AutoEdit = true;
textField.HorizontalAlignment = CCTextAlignment.Center;
textField.VerticalAlignment = CCVerticalTextAlignment.Center;
TrackNode = textField;
TrackNode.Position = pos;
AddChild(textField);
// Register Touch Event
var touchListener = new CCEventListenerTouchOneByOne();
touchListener.OnTouchBegan = OnTouchBegan;
touchListener.OnTouchEnded = OnTouchEnded;
AddEventListener(touchListener);
// The events
bool OnTouchBegan(CCTouch pTouch, CCEvent touchEvent)
{
beginPosition = pTouch.Location;
return true;
}
void OnTouchEnded(CCTouch pTouch, CCEvent touchEvent)
{
if (trackNode == null)
{
return;
}
var endPos = pTouch.Location;
if (trackNode.BoundingBox.ContainsPoint(beginPosition) && trackNode.BoundingBox.ContainsPoint(endPos))
{
OnClickTrackNode(true);
}
else
{
OnClickTrackNode(false);
}
}
public void OnClickTrackNode(bool bClicked)
{
if (bClicked && TrackNode != null)
{
if (!isKeyboardShown)
{
isKeyboardShown = true;
TrackNode.Edit();
}
}
else
{
if (TrackNode != null)
{
TrackNode.EndEdit();
}
}
}
private void OnEndEditing(object sender, ref string text, ref bool canceled)
{
//((CCNode)sender).RunAction(scrollDown);
Console.WriteLine("OnEndEditing text {0}", text);
}
private void OnBeginEditing(object sender, ref string text, ref bool canceled)
{
//((CCNode)sender).RunAction(scrollUp);
Console.WriteLine("OnBeginEditing text {0}", text);
}
void AttachListeners()
{
// Attach our listeners.
var imeImplementation = trackNode.TextFieldIMEImplementation;
imeImplementation.KeyboardDidHide += OnKeyboardDidHide;
imeImplementation.KeyboardDidShow += OnKeyboardDidShow;
imeImplementation.KeyboardWillHide += OnKeyboardWillHide;
imeImplementation.KeyboardWillShow += OnKeyboardWillShow;
imeImplementation.InsertText += InsertText;
}
void DetachListeners()
{
if (TrackNode != null)
{
// Remember to remove our event listeners.
var imeImplementation = TrackNode.TextFieldIMEImplementation;
imeImplementation.KeyboardDidHide -= OnKeyboardDidHide;
imeImplementation.KeyboardDidShow -= OnKeyboardDidShow;
imeImplementation.KeyboardWillHide -= OnKeyboardWillHide;
imeImplementation.KeyboardWillShow -= OnKeyboardWillShow;
imeImplementation.InsertText -= InsertText;
}
}
This is all taken from the link below but needed a bit of additional work to get it working on each platform.
https://github.com/mono/cocos-sharp-samples/tree/master/TextField

Resources