I have an anchor which has three elements. Each element will has to respond for a click event.
I have this as and Android web view app.
Surprisingly click event works in android browser, but when I try that android webview app, nothing happens. Please refer the code below.
I don't know what I am missing so the click events doesn't work in android webview app.
$("#cont2 li a").live('click', function (e) {
//e.preventDefault();
this.blur();
var name = $(this).attr("name");
var staffid = $(this).attr("staffid");
var recordid = $(this).attr("recordid");
var primary = $(this).attr("primary");
if (name == "deletestaff") {
// delete sales staff
var dretVal = confirm("Delete contact staff " + $(this).attr("staffname") + "?");
if (dretVal == false) {
return false;
} else {
var txtprimaryrecordid = $("#txtprimaryrecordid").val();
var txtprimarystaffid = $("#txtprimarystaffid").val();
if (txtprimaryrecordid == 'undefined') {
txtprimaryrecordid = "";
}
if (txtprimarystaffid == 'undefined') {
txtprimarystaffid = "";
}
if (txtprimaryrecordid == recordid) {
$("#txtprimaryrecordid").val("");
}
if (txtprimarystaffid == staffid) {
$("#txtprimarystaffid").val("");
}
$(this).parents('li').remove();
// show deleted item
$('#staffs input[type=checkbox]').each(function () {
var delstaffid = $(this).attr("staffid");
if (staffid == delstaffid) {
$(this).attr("checked", false).checkboxradio("refresh");
}
});
}
}
Got it. Just had to implement WebChromeClient...
private class WebChromeClient extends WebChromeClient{
#Override
public boolean onJsAlert(WebView view, String url, String message,JsResult result)
{
Log.e("alert triggered", message);
return false;
}
}
Related
I am working on a Xamarin.Forms application. I have this tabbed page renderer in iOS:
public class TabbedPageRenderer : TabbedRenderer
{
private MainPage _page;
protected override void OnElementChanged(VisualElementChangedEventArgs e)
{
base.OnElementChanged(e);
if (e.NewElement != null)
{
_page = (MainPage)e.NewElement;
}
else
{
_page = (MainPage)e.OldElement;
}
try
{
var tabbarController = (UITabBarController)this.ViewController;
if (null != tabbarController)
{
tabbarController.ViewControllerSelected += OnTabBarReselected;
}
}
catch (Exception exception)
{
Console.WriteLine(exception);
}
}
private void OnTabBarReselected(object sender, UITabBarSelectionEventArgs e)
{
var tabs = Element as TabbedPage;
var playTab = tabs.Children[4];
if (TabBar.SelectedItem.Title == "Play")
{
if (tabs != null)
{
playTab.Title = "Pause";
playTab.Icon = "pause.png";
}
App.pauseCard = false;
}
else
{
if (tabs != null)
{
playTab.Title = "Play";
playTab.Icon = "play.png";
}
App.pauseCard = true;
}
}
}
This basically changes the icon on my Play tab to pause and play. This is working good in iOS. But I am struggling on how to have the same function (basically convert this to Android) in Android side.
Can any point me to the right direction? Basically help me? :-)
Note: I am pretty new with Android development.
EDIT: This is what it would look like in iOS.
Pause Mode:
Play Mode:
There is a blog post by Xamarin's James Montemagno which explains how to achieve this requirement.
Basically, it uses Custom Tab which inherits from TabbedPage which initialize an event UpdateIcons to be fired on Tab Current Page Changed event CurrentPageChanged
public class MyTabs : TabbedPage
{
//always save a reference to the current page
Page currentPage;
public MyTabs()
{
//create the pages and set the view models
//you could also do this in the page code behind
Children.Add(new TabIconsPage
{
BindingContext = new Tab1ViewModel
{
IsSelected = true
}
});
Children.Add(new TabIconsPage2
{
BindingContext = new Tab2ViewModel()
});
currentPage = Children[0];
//Register for page changes
this.CurrentPageChanged += Handle_CurrentPageChanged;
}
//Update the IsSelected state and trigger an Event that anyone can loop into.
public event EventHandler UpdateIcons;
void Handle_CurrentPageChanged(object sender, EventArgs e)
{
var currentBinding = currentPage.BindingContext as IIconChange;
if (currentBinding != null)
currentBinding.IsSelected = false;
currentPage = CurrentPage;
currentBinding = currentPage.BindingContext as IIconChange;
if (currentBinding != null)
currentBinding.IsSelected = true;
UpdateIcons?.Invoke(this, EventArgs.Empty);
}
}
Now Android needs a custom renderer to subscribe to the UpdateIcons event and perform icon changes
public class MyTabs : TabbedPage
{
//always save a reference to the current page
Page currentPage;
public MyTabs()
{
//create the pages and set the view models
//you could also do this in the page code behind
Children.Add(new TabIconsPage
{
BindingContext = new Tab1ViewModel
{
IsSelected = true
}
});
Children.Add(new TabIconsPage2
{
BindingContext = new Tab2ViewModel()
});
currentPage = Children[0];
//Register for page changes
this.CurrentPageChanged += Handle_CurrentPageChanged;
}
//Update the IsSelected state and trigger an Event that anyone can loop into.
public event EventHandler UpdateIcons;
void Handle_CurrentPageChanged(object sender, EventArgs e)
{
var currentBinding = currentPage.BindingContext as IIconChange;
if (currentBinding != null)
currentBinding.IsSelected = false;
currentPage = CurrentPage;
currentBinding = currentPage.BindingContext as IIconChange;
if (currentBinding != null)
currentBinding.IsSelected = true;
UpdateIcons?.Invoke(this, EventArgs.Empty);
}
}
I am using photon to make a FPS game for android.
Here is the code:
using UnityEngine;
using UnityEngine.UI;
public class SceneLoaderButton : Photon.PunBehaviour {
public string roomName, mapNameGL, password;
public GameObject loadingPan;
public MenuRooms menuManager;
// Use this for initialization
void Start () {
Button btn = GetComponent<Button> ();
btn.onClick.AddListener (ConnectCustomRoom);
}
// Update is called once per frame
void Update () {
}
void ConnectCustomRoom(){
string room = roomName;
RoomInfo[] ri;
ri = PhotonNetwork.GetRoomList ();
bool correct = false;
string passwd, mapName = "";
passwd = password;
foreach (RoomInfo info in ri) {
if (info.name == room) {
if (info.customProperties ["Password"].ToString() == passwd) {
print(info.playerCount + "/" + info.maxPlayers);
if (info.playerCount < info.maxPlayers)
{
correct = true;
}
else
{
menuManager.error("No room for you");
}
mapName = info.customProperties ["MapName"].ToString ();
}
else
{
menuManager.error("Incorrect password");
}
}
}
mapNameGL = mapName;
print(mapNameGL);
if (correct) {
print("Correct");
loadingPan.active = !loadingPan.active;
PhotonNetwork.playerName = "Player" + UnityEngine.Random.Range (1000,9999).ToString();
PhotonNetwork.JoinRoom(room);
}
}
void OnJoinedRoom()
{
print("Joined room: " + roomName);
//We joined room, load respective map
Application.LoadLevel(mapNameGL);
}
}
This is the code from button. It is instantiated and it should join the room, then load the scene. In other scripts, "onjoinedroom" callback works, even if I inherite from Photon.MonoBehaveiour, not from PUNBehaveiour. What is wrong?
based on PUN documentation, it is a virtual member, so you can override that method.
try to change the method to :
override void OnJoinedRoom ()
{
//your codes
}
//or
public override void OnJoinedRoom ()
{
//your codes
}
This class provides a .photonView and all callbacks/events that PUN
can call. Override the events/methods you want to use. By extending
this class, you can implement individual methods as override.
Hope that's help you.
Reference :
PUN Documentation
1.When the device receives push how to automate in Appium so that it will open the push notification and read the text.
i am using following code to tap notification with some needed text. you can use it and do whatever needed (did not update code it long time. some parts can be re-written much better. but still working with every phone i tested):
Page object first:
public class NativeNotificationPage extends Page {
#AndroidFindBy(id= "com.android.systemui:id/notification_panel")
private List<AndroidElement> notificationPanel;
//settings data
#HowToUseLocators(androidAutomation = LocatorGroupStrategy.ALL_POSSIBLE)
#AndroidFindBy(id = "com.android.systemui:id/clear_all_button")
#AndroidFindBy(id = "com.android.systemui:id/dismiss_text")
private List<AndroidElement> clearAllBtn;
//last items
#AndroidFindBy(id = "com.android.systemui:id/latestItems")
private List<AndroidElement> lastItemsContainer;
//events data
#AndroidFindBy(id = "android:id/status_bar_latest_event_content")
private List<AndroidElement> lastItemsContent;
#AndroidFindBy(id = "android:id/title")
private List<AndroidElement> itemTitle;
String itemTitle_Locator_Text = "android:id/title";
#HowToUseLocators(androidAutomation = LocatorGroupStrategy.ALL_POSSIBLE)
#AndroidFindBy (id = "android:id/big_text")
#AndroidFindBy (id = "android:id/text")
private List<AndroidElement> itemText;
String itemText_Phone_Locator_Text = "android:id/text";
String itemText_Tablet_Locator_Text = "android:id/big_text";
#AndroidFindBy(id = "android:id/time")
private List<AndroidElement> itemTime;
public NativeNotificationPage(WebDriver driver) {
super(driver);
}
public boolean isNativeNotificationPage() {
System.out.println(" check 'Notification' Screen loaded");
boolean bool;
setFastLookTiming();
bool = !notificationPanel.isEmpty();
setDefaultTiming();
return bool;
}
public boolean isNativeNotificationPage(int sec) {
System.out.println(" check 'Notification' Screen loaded");
boolean bool;
setLookTiming(sec);
bool = !notificationPanel.isEmpty();
setDefaultTiming();
return bool;
}
public boolean isClearAllBtnLoaded() {
System.out.println(" check 'Clear' button loaded");
boolean bool;
setLookTiming(3);
bool = !clearAllBtn.isEmpty();
setDefaultTiming();
return bool;
}
public int getLastItemsContentSize() {return lastItemsContent.size();}
public String getItemTitle(int num) {
try {
return lastItemsContent.get(num).findElement(MobileBy.className("android.widget.TextView")).getText();
} catch (Exception e) {
return null;
}
}
public String getItemText(int num) {
if (isPhone()) {
List<MobileElement> item = lastItemsContent.get(num).findElements(MobileBy.className("android.widget.TextView"));
String tmp = null;
for (int i=1;i<item.size();i++) {
if (tmp == null)
tmp = item.get(i).getText();
else
tmp = tmp + "," +item.get(i).getText();
}
return tmp;
} else {
setLookTiming(3);
if (lastItemsContent.get(num).findElements(MobileBy.id(itemText_Tablet_Locator_Text)).isEmpty()) {
setDefaultTiming();
return lastItemsContent.get(num).findElement(MobileBy.id(itemText_Phone_Locator_Text)).getText();
} else {
setDefaultTiming();
return lastItemsContent.get(num).findElement(MobileBy.id(itemText_Tablet_Locator_Text)).getText();
}
}
}
public boolean tapClearAllBtn() {
System.out.println(" tap 'Clear' button");
return tapElementInList_Android(clearAllBtn, 0);
}
public boolean tapNotificationByNum(int num) {
return tapElementInList_Android(lastItemsContent, num);
}
}
Now in test code:
public Boolean tapNotificationByTitleAndText_Android(String neededTitle, String neededText, AppiumDriver driver) {
((AndroidDriver) driver).openNotifications();
sleep(1);
nativeNotificationPage = new NativeNotificationPage(driver);
assertTrue("Native notification page is NOT loaded", nativeNotificationPage.isNativeNotificationPage());
int itemsListSize = nativeNotificationPage.getLastItemsContentSize();
System.out.println(" number of notifications is: " + itemsListSize);
assertTrue("Number of notifications is 0", itemsListSize != 0);
String title, text;
for (int i = 0; i < itemsListSize; i++) {
title = nativeNotificationPage.getItemTitle(i);
text = nativeNotificationPage.getItemText(i);
System.out.println(" notification title is: " + title);
System.out.println(" notification text is: " + text);
.....
return nativeNotificationPage.tapNotificationByNum(i);
}
return false;
}
You can open notifications pane using following inbuilt AndroidDriver's method.
driver.openNotifications();
If you want to scroll down to a specific Push, use following code -
WebElement element = driver.findElement(By.name("Element Name"));
HashMap<String, String> arguments = new HashMap<String, String>();
arguments.put("element", element.getId());
(JavascriptExecutor)driver.executeScript("mobile: scrollTo", arguments);
Note - driver is of type AndroidDriver. If not, then you should type-cast it.
Go through this library for better understanding of functions - https://github.com/appium/java-client
First things is, what type of push notification you are use.
two type of push notification firebase offer :
1.Notification
2.Data payload.
guys.
I'm trying to use vk api sdk in Xamarin.Android. I create a request:
var token = VKHelper.GetVkUserToken(App.Data.Setting.List);
var iparams = new Dictionary<string, Java.Lang.Object>();
iparams.Add(VKApiConst.UserId, VKBuffer.Friend.Id);
iparams.Add("type", "invite");
iparams.Add("access_token", token);
v = new VKRequest("apps.sendRequest", new VKParameters(iparams));
By clicking in button I call ExecuteWithListener:
v.ExecuteWithListener(new ReqvList(new Action(o =>
{
RunOnUiThread(() =>
{
if (o.IsComplete)
{
try
{
showCustomAlert(Resource.Drawable.checkmark, GetString(Resource.String.SentInvite), Android.Graphics.Color.Argb(100, 0, 0, 200));
}
catch { }
}
else
{
try
{
showCustomAlert(Resource.Drawable.ic_post, GetString(Resource.String.NotSentInvite) + "\n" + GetString(o.MessageId), Android.Graphics.Color.Argb(100, 200, 0, 0));
}
catch { }
}
});
})));
Listener:
public class ReqvList : VKRequest.VKRequestListener
{
Action<CallBackVKResponse> Complete;
CallBackVKResponse callBackVKResponse = new CallBackVKResponse
{
IsComplete = false,
MessageId = 0
};
public ReqvList(Action<CallBackVKResponse> Complete)
{
this.Complete = Complete;
}
public override void OnComplete(VKResponse p0)
{
base.OnComplete(p0);
var response = p0.Json.ToString();
callBackVKResponse.IsComplete = true;
Complete(callBackVKResponse);
}
public override void OnError(VKError p0)
{
int errorCode = p0.ApiError != null ? p0.ApiError.ErrorCode : 0;
callBackVKResponse.IsComplete = false;
if (errorCode == 15)
callBackVKResponse.MessageId = Resource.String.VkInviteError;
Complete(callBackVKResponse);
base.OnError(p0);
}
}
Summary: if I press to invite a friend, I will see a "vkontakte" dialog window with suggest message (here you can accept or skip). If I press "invite" a friend which has disabled to invite him (or her) then it works fine. This is:
....
else
{
try
{
showCustomAlert(Resource.Drawable.ic_post, GetString(Resource.String.NotSentInvite) + "\n" + GetString(o.MessageId), Android.Graphics.Color.Argb(100, 200, 0, 0));
}
catch { }
}
....
But if a user has enabled to invite him (or her) then listener won't work and my app will freeze. In the phone you can press back button and the app will unfreez and after I can press again the button - invite will has worked fine. Listener OnComplete works only the second time. This is:
...
if (o.IsComplete)
{
try
{
showCustomAlert(Resource.Drawable.checkmark, GetString(Resource.String.SentInvite), Android.Graphics.Color.Argb(100, 0, 0, 200));
}
catch { }
}
...
Help please.
Usually I called the shouldOverrideUrlLoading method to call the email client in android, if the webview contains below code
test#test.com
but current webview has written like below code
<span class="underline" onclick="openMail('test#test.com')">test#test.com</span>
So if I use the below code
webview.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.contains("test#test.com")) {
Intent intent = new Intent(Intent.ACTION_SENDTO);
intent.setData(Uri.parse("mailto:" + "test#test.com"));
startActivity(intent);
} else {
view.loadUrl(url);
}
return true;
}
});
webview.loadUrl(url);
}
JavaScript code like this
$(function(){
$(".question").on("click",function(){
if( $(this).next(".answer").css("display") == "none" ){
$(this).next(".answer").show();
$(this).addClass("unfold");
} else {
$(this).next(".answer").hide();
$(this).next(".answer").find(".answerinner").hide();
$(this).removeClass("unfold");
}
});
$(".title_h5").on("click",function(){
if( $(this).next(".answerinner").css("display") == "none" ){
$(this).next(".answerinner").show();
} else {
$(this).next(".answerinner").hide();
}
});
});
var browser = {
versions: function () {
var u = navigator.userAgent, app = navigator.appVersion;
return {
ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/),
android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1,
iPhone: u.indexOf('iPhone') > -1,
iPad: u.indexOf('iPad') > -1,
};
}(),
}
function connectWebViewJavascriptBridge(callback) {
if (window.WebViewJavascriptBridge) {
callback(WebViewJavascriptBridge)
} else {
document.addEventListener('WebViewJavascriptBridgeReady', function() {
callback(WebViewJavascriptBridge)
}, false)
}
}
function openMail(mailAddress) {
if (browser.versions.iPhone || browser.versions.iPad || browser.versions.ios) {
connectWebViewJavascriptBridge(function(bridge) {
var uniqueId = 1
bridge.init(function(message, responseCallback) {
var data = { 'Javascript Responds':'Wee!' }
responseCallback(data)
})
bridge.registerHandler('testJavascriptHandler', function(data, responseCallback) {
var responseData = { 'Javascript Says':'Right back atcha!' }
responseCallback(responseData)
})
var data = mailAddress;
bridge.send(data, function(responseData) {
})
});
}
if (browser.versions.android) {
window.email.open(mailAddress);
}
}
then it's not open the email client when I click the email in the webview.
Even it's not hit the click even.
I checked the startsWith also
Any Advise ??
Thanks in Advance.