Placing an Admob banner at the bottom of screen - c#

I have added a Admob banner to a scene in my app by using the example from: https://forums.xamarin.com/discussion/51779/cocossahrp-and-admob.
The ad displays at the top of the screen but I want to display it at the bottom. I couldn't find any CocosSharp examples but I did find one for cocos2d-x(last post): http://discuss.cocos2d-x.org/t/admob-bottom-placement-tutorial-v3-0/13854/11
I have tried this with my code(see below) but can't get it working. Something I have noticed though is if I change the LayoutParams from 200 to size.Y the ad banner appears in the middle of the screen instead of the top but this happens even when AlignParentBottom or Gravity.Bottom is not used.
Using a RelativeLayout with AddRule:
Android.Graphics.Point size = new Android.Graphics.Point();
prActivity.WindowManager.DefaultDisplay.GetSize(size);
RelativeLayout.LayoutParams adParams = new RelativeLayout.LayoutParams(
size.X,
200);
var bannerAd = new AdView(prActivity);
bannerAd.AdSize = AdSize.SmartBanner;
bannerAd.AdUnitId = "ca-app-pub-3940256099942544/6300978111"; // Test UnitId
bannerAd.LayoutParameters = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.WrapContent);
var lcRequestbuilder = new AdRequest.Builder();
bannerAd.LoadAd(lcRequestbuilder.Build());
adParams.AddRule(LayoutRules.AlignParentBottom); // Rule to place ad at the bottom
prActivity.AddContentView(bannerAd, adParams);
ScheduleOnce(t =>
{
bannerAd.BringToFront();
}, 3f);
Using a LinearLayout with Gravity:
Android.Graphics.Point size = new Android.Graphics.Point();
prActivity.WindowManager.DefaultDisplay.GetSize(size);
LinearLayout.LayoutParams adParams = new LinearLayout.LayoutParams(
size.X,
200);
var bannerAd = new AdView(prActivity);
bannerAd.AdSize = AdSize.SmartBanner;
bannerAd.AdUnitId = "ca-app-pub-3940256099942544/6300978111"; // Test UnitId
bannerAd.LayoutParameters = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.WrapContent);
var lcRequestbuilder = new AdRequest.Builder();
bannerAd.LoadAd(lcRequestbuilder.Build());
adParams.Gravity = GravityFlags.Bottom; // Gravity Flag to place ad at the bottom
prActivity.AddContentView(bannerAd, adParams);
ScheduleOnce(t =>
{
bannerAd.BringToFront();
}, 3f);

I use AdMob Ad in this way in my App and it's work for me(Ad is in the bottom of the screen) :
private static final String AD_UNIT_ID = "";
private AdView adView;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout.LayoutParams adParams = new LinearLayout.LayoutParams(getWindowManager().getDefaultDisplay().getWidth(), (getWindowManager().getDefaultDisplay().getHeight() + getWindowManager().getDefaultDisplay().getHeight()) - 100);
adView = new AdView(this);
adView.setAdSize(AdSize.BANNER);
adView.setAdUnitId(AD_UNIT_ID);
adView.setBackgroundColor(Color.TRANSPARENT);
addContentView(this.adView, adParams);
}
getWidth method of Display is deprecated but still i am using it.

Related

How to programmatically add a Vertical or Horizontal StackView to a view

I'm able to add a Vertical and Horizontal StackView programmatically to my main view but the view is not performing any stacking type layout.
Here is what I have so far:
// create vertical stack
var viewSize = new CGSize(200, 150);
var viewLocation = new CGPoint(0, 0);
var viewRectangle = new CGRect(viewLocation, viewSize);
var frame = new CGRect(0, 0, 200, 20);
var stackView = new NSStackView(viewRectangle);
var button1 = new NSButton(frame) {
Title = "Button 1"
};
var frame2 = new CGRect(0, 10, 200, 20);
var button2 = new NSButton(frame2) {
Title = "Button 2"
};
// show background to help see size and position
stackView.WantsLayer = true;
stackView.Layer.BackgroundColor = new CGColor(150, 0, 150, 1);
stackView.Orientation = NSUserInterfaceLayoutOrientation.Vertical;
stackView.Alignment = NSLayoutAttribute.Top;
stackView.Distribution = NSStackViewDistribution.Fill;
stackView.Spacing = 10;
stackView.AddSubview(button1);
stackView.AddSubview(button2);
stackView.NeedsLayout = true;
frame1.AddSubview(stackView);
Screenshot below.
The top view is a manually created Vertical Stack in Interface Builder. The bottom is the programmatic one created from the code above:
Update:
I found some example code in the Xamarin iOS documentation:
https://learn.microsoft.com/en-us/xamarin/ios/user-interface/controls/uistackview
There are some properties I can't find but some of it is working.
The main enabling difference is that you need to use the addArrangedSubViews() method instead of addSubviews() method.
stackView.AddArrangedSubview(button);
Visual Studio for Mac using Xamarin and C#

GMap.NET how can I make an accurate routing?

So what I am trying to do is showing a route on a winforms application using the GMap.NET nugget.
But the problem I encountered is that it doesn't show the route using the roads. It's literately showing the shortest distances between 2 points, so to make it more accurate I did an extra API call to google maps Directions. So I have some extra points to make it more accurate but still between 2 points its just a straight line, not on roads.
route problem
Here you can see how I am loading the points.
public void ShowRoute(Coordinate[] coordinates)
{
if (coordinates.Length > 1)
{
List<PointLatLng> points = new List<PointLatLng>();
foreach (var cor in coordinates)
{
Coordinate c = geo.ConvertCoordinates(cor);
var corstring = geo.GetAdresByCor(c);
var point = new PointLatLng(Convert.ToDouble(c.Latitude.Replace(".", ",")), Convert.ToDouble(c.Longitude.Replace(".", ",")));
var marker = new GMarkerGoogle(point, GMarkerGoogleType.pink_pushpin);
routeMarkers.Markers.Add(marker);
}
var routes = geo.DirectionsByCor(coordinates);
foreach (var route in routes)
{
foreach (var step in route.Legs[0].Steps)
{
var point = new PointLatLng(step.EndLocation.Latitude, step.EndLocation.Longitude);
points.Add(point);
}
}
var r = new GMapRoute(points, "route");
var routesOverlay = new GMapOverlay("routes");
routesOverlay.Routes.Add(r);
map.Overlays.Add(routeMarkers);
map.Overlays.Add(routesOverlay);
}
}
Here is how my Map is loaded.
private void map_Load(object sender, EventArgs e)
{
GMapProviders.GoogleMap.ApiKey = Properties.Settings.Default.ApiKey;
geo = new GeocoderXY();
map.MouseWheelZoomEnabled = true;
map.DragButton = MouseButtons.Left;
map.MapProvider = GMapProviders.GoogleMap;
lng = 3.7074218;
lat = 51.008157;
GMapMarker marker = new GMarkerGoogle(new PointLatLng(lat, lng), GMarkerGoogleType.blue_pushpin);
searchMarker = marker;
markers.Markers.Add(marker);
markers.Markers.Add(mouseMarker);
map.Position = new NET.PointLatLng(lat, lng);
map.MouseWheelZoomType = NET.MouseWheelZoomType.MousePositionWithoutCenter;
map.MinZoom = 5;
map.MaxZoom = 100;
map.Zoom = 15;
map.ShowCenter = false;
}
I don't see what I'm doing wrong, if someone does see it, please let me know!
Thanks
Still it's not clear why you're doing extra calls.Anyway, to get a route all it's needed a start and end locations and call GetDirections (apparently GoogleMapProvider is obsolete):
GDirections myDirections;
var route = GMapProviders.GoogleMap.GetDirections(out myDirections, start, end, false, false, false, false, false);
then use the directions to draw
var route = new GMapRoute(myDirections.Route, "route");
var routesOverlay = new GMapOverlay("routes");
routesOverlay.Routes.Add(route);
Unfortunately I dont have the VS to test but you got the idea.

Add pin on click Xamarin.Forms.Maps

I want to add a new pin on clicking on the map using Xamarin.Forms.Maps.
After searching , I found that I have to use TKCustomMap plugin .. but it didn't show on the map .. just empty area
and this is my code
double lit = 2.394;// double.Parse(Center.CenterLocationX);
double longt = 43.2352;// double.Parse(Center.CenterLocationY);
TK.CustomMap.Position position = new TK.CustomMap.Position(lit, longt);
TK.CustomMap.MapSpan span = TK.CustomMap.MapSpan.FromCenterAndRadius(position, TK.CustomMap.Distance.FromMiles(0.5));
TK.CustomMap.TKCustomMap map = new TK.CustomMap.TKCustomMap(span);
map.IsShowingUser = true;
map.MapType = TK.CustomMap.MapType.Street;
TK.CustomMap.TKCustomMapPin pin = new TK.CustomMap.TKCustomMapPin()
{
//Address = "Test",
//Label = "Test",
Position = position,
IsDraggable = true
//Type = PinType.SearchResult
};
map.MapClicked += (x, y) =>
{
SharedTools.MakeToast("Clicked");
};
//map.Pins.Add(pin);
map.Pins = new List<TK.CustomMap.TKCustomMapPin>() { pin };
map.MoveToMapRegion(span);
layout.Content = map;
I want to solve this, or any other idea to add pin on click
I used your code in my demo, i got the result like the following screenshot(If you cannot see the band of google, you should check the API_KEY, if it is correct.)
<meta-data android:name="com.google.android.maps.v2.API_KEY" android:value="API_KEY" />
Then i changed the lit to 37, longt to -122 and add pin on click.I can see the map and get the following result. Please check your lit and longt, if the value is legal
There is my code.
public partial class MainPage : ContentPage
{
TK.CustomMap.TKCustomMap map;
TK.CustomMap.Position position;
public MainPage()
{
InitializeComponent();
//37,-122
double lit = 37;// double.Parse(Center.CenterLocationX);
double longt = -122;// double.Parse(Center.CenterLocationY);
position = new TK.CustomMap.Position(lit, longt);
TK.CustomMap.MapSpan span = TK.CustomMap.MapSpan.FromCenterAndRadius(position, TK.CustomMap.Distance.FromMiles(0.5));
map = new TK.CustomMap.TKCustomMap(span);
map.IsShowingUser = true;
map.MapType = TK.CustomMap.MapType.Street;
map.MapClicked += OnMapClicked;
Content = map;
}
private void OnMapClicked(object sender, TKGenericEventArgs<Position> e)
{
TK.CustomMap.TKCustomMapPin pin = new TK.CustomMap.TKCustomMapPin()
{
//Address = "Test",
//Label = "Test",
Position = position
,
IsDraggable = true
//Type = PinType.SearchResult
};
map.Pins = new List<TK.CustomMap.TKCustomMapPin>() { pin };
}
}
Here is my demo.Hope this can help you.
https://github.com/851265601/TKGoogleMapsDemo

UISearchBar not resizing on phone rotation

I am having an issue where my UISearchBar does not resize on phone rotation unless I touch on the search bar so that it has focus (see images below).
The search bar is created and added to a UIMapView as a subview. See code.
Searchbar creation:
public UISearchController DefineSearchController()
{
_searchResultsController = new SearchResultsVC(_mapView);
_searchResultsController.searchItemSelected += PlaceSelect;
_searchUpdater = new SearchResultsUpdator();
_searchUpdater.UpdateSearchResults += _searchResultsController.Search;
//add the search controller
var searchController = new UISearchController(_searchResultsController)
{
SearchResultsUpdater = _searchUpdater
};
var scb = searchController.SearchBar;
scb.SizeToFit();
scb.SearchBarStyle = UISearchBarStyle.Minimal;
var img = UIImage.FromBundle("tabSpace");
scb.SetBackgroundImage(img, UIBarPosition.Top, UIBarMetrics.Default);
var textField = scb.ValueForKey(new NSString("searchField")) as UITextField;
if (textField != null)
{
var backgroundView = textField.Subviews[0];
if (backgroundView != null)
{
backgroundView.BackgroundColor = UIColor.White;
backgroundView.Layer.BorderColor = AppColour.PersianBlue.GetUIColour().CGColor;
backgroundView.Layer.BorderWidth = 1;
backgroundView.Layer.CornerRadius = 10;
backgroundView.ClipsToBounds = true;
}
}
var localEnterPoI = NSBundle.MainBundle.LocalizedString("placeHolderSearchForLocation", "Enter a PoI to search for");
scb.Placeholder = localEnterPoI;
searchController.Delegate = new SearchControllerDelegate();
searchController.HidesNavigationBarDuringPresentation = false;
return searchController;
}
Added to the subview:
//Define Search Controller
_mapSearchManager = new MapSearchManager(_mapView);
_searchController = _mapSearchManager.DefineSearchController();
var scb = _searchController.SearchBar;
_mapView.AddSubview(scb);
NSLayoutConstraint.ActivateConstraints(new NSLayoutConstraint[]{
scb.TopAnchor.ConstraintEqualTo(_mapView.TopAnchor, 30),
scb.LeadingAnchor.ConstraintEqualTo(_mapView.LeadingAnchor, 10),
scb.TrailingAnchor.ConstraintEqualTo(_mapView.LeadingAnchor, -10),
});
I heave search extensively and was only able to find one similar issue:
UISearchBar doesn't resize when frame is resized in IOS 11
I implementing both of suggestion but it didn't make any difference.
Has anyone else encounted this or know what a possible solution might be.
Cheers

Monotouch dimensions not making sense

I have the following in my AppDelegate:
const string fileName = "Content/tandc.html";
window = new UIWindow(UIScreen.MainScreen.Bounds);
var webView = new UIWebView(new RectangleF(0,-20, 300, 300));
string localHtmlUrl = Path.Combine(NSBundle.MainBundle.BundlePath, fileName);
webView.LoadRequest(new NSUrlRequest(new NSUrl(localHtmlUrl, false)));
webView.ScalesPageToFit = false;
webView.Opaque = false;
webView.BackgroundColor = UIColor.Clear;
var webelement = new UIViewElement("", webView, true);
var agree = new StyledStringElement("Agree", () => Console.WriteLine("test"));
var noAgree = new StyledStringElement("Whatever", () => Console.WriteLine("test"));
var headerView = new UIImageView(new RectangleF(0, 0, 640, 85))
{
Image = UIImage.FromFile("Images/SafeWork_TandC_640_165.png")
};
var section = new Section()
{
HeaderView = headerView
};
window.RootViewController = new DialogViewController(new RootElement("Login") {
section,
new Section()
{
webelement
},
new Section()
{
agree, noAgree
}
});
window.MakeKeyAndVisible();
return true;
My question is - why are the dimensions for the WebView completely not related to the dimensions for the actual window? The header image has a width of 640px to make it the width of the iPhone yet the webview has a width of 300 to make it fit - 400 is way way too big for the screen and it actually goes off screen if set to that?
short answer: retina.
Window dimensions are in non-retina pixels, to allow legacy app to work well. So, a 640px wide image will take 320px of screen unit if your device supports retina display.

Categories

Resources