I have the following minimal example of an app using Xamarin.Forms (version 1.2.3) and a MasterDetailPage (similar to: "Show "Back to Menu" Button in iOS NavigationBar with Xamarin.Forms"):
public static class App
{
static MasterDetailPage MDPage;
public static Page GetMainPage()
{
MDPage = new MasterDetailPage {
Master = new ContentPage {
Title = "Master",
Icon = Device.OS == TargetPlatform.iOS ? "menu.png" : null,
Content = new Button {
Text = "Open detail",
Command = new Command(o => {
MDPage.Detail = new NavigationPage(new ContentPage());
MDPage.IsPresented = false;
}),
},
},
Detail = new NavigationPage(new ContentPage()),
};
MDPage.IsPresentedChanged += (sender, e) => Console.WriteLine(DateTime.Now + ": " + MDPage.IsPresented);
return MDPage;
}
}
(hosted on GitHub)
When opening or closing the MasterPage via button click on Android, the IsPresentedChanged event is triggered three times instead of once. According to the command line output the IsPresented property is either toggling as True-False-True or False-True-False, respectively.
Opening or closing using a swipe gesture or tapping on the DetailPage does work well. On iOS there is no problem at all.
Is there something I'm doing wrong? Or is there a simple workaround to get a reliable event?
Ok, with the current version 1.4.0 of Xamarin.Forms the issue seems to be fixed. Opening the slide-out menu yields exactly one "True", closing it yields "False" - just as expected.
Related
Consider a tabbar with "home" and "profile" buttons, when i click on either i switch between two pages, on the "home" page the user can navigate multiple times up in the navigationstack still having the focus on the "home" tab indicating that this is where the user came from.
Now, on iOS whenever the user clicks on "home" from high up in the navigationstack the user is popped to root and all is well, this is not the case on android however, on android the user has to pop one page at a time by clicking on the backbutton to get to the root.
Is this intended behavior, am i doing something wrong, does someone have a clue as to what i can do to get the desired behavior?
This is the intended behavior between iOS and Android .
If you need to make the Android has the same effect with iOS, you need to custom TabbedPageRenderer to achieve that. And the bottom tab bar effect can custom a FreshTabbedNavigationContainer . Last, we will use MessagingCenter to send message to Forms to pop to Root Page.
For example, CustomFreshTabbedNavigationContainer class:
public class CustomFreshTabbedNavigationContainer : FreshTabbedNavigationContainer
{
public CustomFreshTabbedNavigationContainer()
{
On<Android>().SetToolbarPlacement(ToolbarPlacement.Bottom);
MessagingCenter.Subscribe<object>(this, "Hi", (sender) =>
{
// Do something whenever the "Hi" message is received
PopToRoot(true);
});
}
}
Used in App.xaml.cs:
public App()
{
InitializeComponent();
var container = new CustomFreshTabbedNavigationContainer();
container.AddTab<FirstPageModel>("Home", default);
container.AddTab<ProfilePageModel>("Profile", default);
MainPage = container;
}
Now we will create a CustomTabbedPageRenderer in Android:
public class CustomTabbedPageRenderer : TabbedPageRenderer, BottomNavigationView.IOnNavigationItemSelectedListener
{
public CustomTabbedPageRenderer(Context context) : base(context)
{
}
int previousItemId = 0;
bool BottomNavigationView.IOnNavigationItemSelectedListener.OnNavigationItemSelected(IMenuItem item)
{
base.OnNavigationItemSelected(item);
if (item.IsChecked)
{
if (previousItemId != item.ItemId)
{
previousItemId = item.ItemId;
}
else
{
Console.WriteLine("ok");
MessagingCenter.Send<object>(this, "Hi");
}
}
return true;
}
}
The effect:
Note: If need to have the same effect with the top Tabbar in Android, there is different code in CustomTabbedPageRenderer. You can have a look at this discussion.
I am using appium and webdriverIO to automate android native app. I need to perform scroll down and i have used
ele.scrollIntoView(true) //this returns not yet implemented error
is there any other way to scroll down?
I don't used java script to scroll down. but I have already given a detail answer with different approach (by some text, element and screen size). Please have a look on it.
How to reach the end of a scroll bar in appium?
Hope it will help.
I have find a way to perform swipe down by calling JsonWireProtocol api directly from my code.
https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol
here is my code
module.exports.scrollAndroid = function (ele) {
console.log('driver.sessionID = ', driver.sessionId);
while (!$(ele).isDisplayed()) { . //$(ele)=$(//xpath or any other attribute)
this.scrollAPICall();
driver.pause(3000);
}
};
module.exports.scrollAPICall = function () {
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
console.log("result status >> ", this.status);
console.log("result text >> ", this.responseText);
};
url1 = `http://127.0.0.1:4723/wd/hub/session/${driver.sessionId}/touch/flick`;
xhttp.open('POST', url1);
console.log("URL >> ", url1)
xhttp.setRequestHeader("Content-Type", "application/json");
xhttp.setRequestHeader("charset", "UTF-8");
xhttp.send(JSON.stringify({
xspeed: 10,
yspeed: -100,
}));
if you want to scroll up then give yspeed as + value. ex:100
You can achieve a scroll down by performing a Screen Swipe Up action. Implementation of swipe class can be found from Boilerplate project. The Gestures.js class has all required functions. Here is the link to class
Please keep in mind that the swipe is performed based on the percentage. Once you implement this Gestures class you can then use it like below:
while(!element.isDisplayed()) {
Gestures.swipeUp(0.5)
}
I'm building a little browser app using android webview and I've been using window.getSelection() in javascript to get the nature of any text selected by the user and show a custom context menu based on the type of the selection i.e. whether it's a range, a carat, whether it's in a contenteditable etc.
This works fine unless the selection is in an iframe, then the browser security measures kick in and prevent me sniffing what has been selected using window.getSelection(). How can I workaround this?
Ideally I need a way to get better information about what was selected from the webview or if that's not possible I need a way to sniff whether the selection occurred in an iframe so I can disable my custom context menu logic and fallback to the default android context menu.
UPDATE/FURTHER CLARIFICATION 07/05/2019:
Seems I wasn't clear enough in my initial description...
My goal is to have a visually and functionally custom menu when selecting content in the webview that can cut/copy/paste as the standard context menu does in any part of the page/iframes etc. e.g.
I realised my original approach using javascript to detect the type of selection and to perform the cut/copy/paste was wrong because it will be blocked by cross origin security in iframes.
What I need is a native android/webview based approach. I've discovered that I can sniff the type of selection in the webview by looking at the items in mode.getMenu() on onActionModeStarted. This will allow me to show the correct buttons in my custom menu UI but I have been unable to manually trigger the same logic that gets called when cut/copy/paste is clicked. I thought I found the solution with webView.performAccessibilityAction(AccessibilityNodeInfo.ACTION_CUT, null); but this doesn't work for some reason so I guess my question really is how can I manually trigger cut/copy/paste on the selected text from webview without using javascript? or any other approach that will allow me to have a custom selection menu with lots of options based on what was selected without hitting the browser security limitations?
Okay I figured out how roughly how to do this.
Step 1) In your activity, override onActionModeStarted and check the menu items available in the default context menu. This gives you a clue as to what the type of selection is and which buttons you will need to show in your custom menu. Also it gives you a reference to the item ID which you can use to later to trigger the action e.g.
systemSelectionMenu = mode.getMenu(); // keep a reference to the menu
MenuItem copyItem = systemSelectionMenu.getItem(0); // fetch any menu items you want
copyActionId = copyItem.getItemId(); // store reference to each item you want to manually trigger
Step 2) Instead of clearing the menu, use setVisible() to hide each menu item you want a custom button for e.g.
copyItem.setVisible(false);
Step 3) In your custom button onclick event you can trigger the copy action using:
myActivity.systemSelectionMenu.performIdentifierAction(myActivity.copyActionId, 0)
You can retrieve iframe's selection only if it has the same origin. Otherwise, you have no chances to track any iframe's events(clicks, touches, key presses, etc.).
const getSelectedText = (win, doc) => {
const isWindowSelectionAvailable = win && typeof win.getSelection != "undefined";
if (isWindowSelectionAvailable) {
return win.getSelection().toString();
}
const hasDocumentSelection = doc && typeof doc.selection != "undefined" && doc.selection.type == "Text";
if (hasDocumentSelection) {
return doc.selection.createRange().text;
}
return '';
}
const doIfTextSelected = (win, doc, cb) => () => {
const selectedText = getSelectedText(win, doc);
if (selectedText) {
cb(selectedText);
}
}
const setupSelectionListener = (win, doc, cb) => {
doc.onmouseup = doIfTextSelected(win, doc, cb);
doc.onkeyup = doIfTextSelected(win, doc, cb);
}
const getIframeWinAndDoc = (iframe) => {
try {
const doc = iframe.contentDocument || iframe.contentWindow.document;
const win = iframe.contentWindow || iframe.contentDocument.defaultView;
return { win, doc };
} catch (e) {
console.error(`${e}`);
return {};
}
}
const callback = console.log;
setupSelectionListener(window, document, callback);
document.querySelectorAll('iframe').forEach(iframe => {
const { win, doc } = getIframeWinAndDoc(iframe, console.log);
// Only for same origin iframes due to https://en.wikipedia.org/wiki/Same-origin_policy
if (win && doc) {
setupSelectionListener(win, doc, callback);
}
})
<h3>Select me</h3>
<div class="container">
<iframe src="https://teimurjan.github.io"></iframe>
</div>
This issue varying from browser to other if it works with internet explorer so it may fall with chrome
Try this
App.util.getSelectedText = function(frameId) {
var frame = Ext.getDom(frameId);
var frameWindow = frame.contentWindow;
var frameDocument = frameWindow.document;
if (frameDocument.getSelection) {
return frameDocument.getSelection();
}
else if (frameDocument.selection) {
return frameDocument.selection.createRange().text;
}
};
Hope it runs fine
Main problem is the window.getSelection() will return selection only for the main context/window. As iframe is the other window and other context, you should call getSelection() from iframe which is "current".
in my Xamarin.Forms App I have an Page which indicates an GoogleMap.
Everything is working perfect, but when I click on an InfowWindow from a pin, i cant open a new detailpage. The App hangs and I can do nothing with the App. I get no error message.
But its working in iOS.
Heres the Code:
private void MapObjekt_InfoWindowClicked(object sender, InfoWindowClickedEventArgs e)
{
App.locator.StopListeningAsync();
App.locator.PositionChanged -= Locator_PositionChanged;
objektliste detailPage = new objektliste();
App.mdp.Detail = detailPage;
}
Whats my fault ?
Problem was, that I have to open the Page in the Mainthread like this:
Device.BeginInvokeOnMainThread(() => { App.mdp.Detail = detailPage; });
I'm trying to use Stripe Checkout inside a WebView (both in Android and in iOS).
If I run the demo checkout in this page from Google Chrome from mobile it opens a new web page and everything works fine.
When I try to run the demo from a WebView (which I expect to behave in a completely similar way) it does not work and gives me a
Sorry, there was a problem loading Checkout.
If this persists, please try a different browser.
I thought that it is not made for mobile, but this is not true because from Google Chrome works perfectly fine.
Any suggestions to make it work?
This is the only way I managed to work with Stripe Checkout on webviews (I used Xamarin):
Install Plugin.Share from nuget (project, add newget packages both in shared and specific mobile project folders)
Try out this code to see that checkout works fine:
using System;
using Xamarin.Forms;
using Plugin.Share;
using Plugin.Share.Abstractions;
namespace stripewebviewtest
{
public class App : Application
{
public App ()
{
Button btn = new Button ();
btn.Text = "Click on me!";
// The root page of your application
MainPage = new ContentPage {
Content = new StackLayout {
VerticalOptions = LayoutOptions.Center,
Children = {
new Label {
XAlign = TextAlignment.Center,
Text = "Welcome to Xamarin Forms!"
},
btn
}
}
};
btn.Clicked += (object sender, EventArgs e) => {
var url = "https://stripe.com/docs/checkout";
CrossShare.Current.OpenBrowser (url, new BrowserOptions {
ChromeShowTitle = true,
ChromeToolbarColor = new ShareColor {
A = 255,
R = 118,
G = 53,
B = 235
},
UseSafairReaderMode = false,
UseSafariWebViewController = false
});
};
}
protected override void OnStart ()
{
// Handle when your app starts
}
protected override void OnSleep ()
{
// Handle when your app sleeps
}
protected override void OnResume ()
{
// Handle when your app resumes
}
}
}
Run the project on a device
Click on "Click on me!" button
Click on "Pay with Card" button on the Webview
↝