I'm new to cocossharp. I installed cocossharp templates for visual studio, when i select a new cocossharp android game, and run the application, all I get is a black screen with a logo at the top. From the code, I believe i am supposed to get a blue screen with a label written
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
// Get our game view from the layout resource,
// and attach the view created event to it
CCGameView gameView = (CCGameView)FindViewById(Resource.Id.GameView);
gameView.ViewCreated += LoadGame;
}
void LoadGame(object sender, EventArgs e)
{
CCGameView gameView = sender as CCGameView;
if (gameView != null)
{
var contentSearchPaths = new List<string>() { "Fonts", "Sounds" };
CCSizeI viewSize = gameView.ViewSize;
int width = 1024;
int height = 768;
// Set world dimensions
gameView.DesignResolution = new CCSizeI(width, height);
// Determine whether to use the high or low def versions of our images
// Make sure the default texel to content size ratio is set correctly
// Of course you're free to have a finer set of image resolutions e.g (ld, hd, super-hd)
if (width < viewSize.Width)
{
contentSearchPaths.Add("Images/Hd");
CCSprite.DefaultTexelToContentSizeRatio = 2.0f;
}
else
{
contentSearchPaths.Add("Images/Ld");
CCSprite.DefaultTexelToContentSizeRatio = 1.0f;
}
gameView.ContentManager.SearchPaths = contentSearchPaths;
CCScene gameScene = new CCScene(gameView);
gameScene.AddLayer(new GameLayer());
gameView.RunWithScene(gameScene);
}
}
public class GameLayer : CCLayerColor
{
// Define a label variable
CCLabel label;
public GameLayer() : base(CCColor4B.Blue)
{
// create and initialize a Label
label = new CCLabel("Hello CocosSharp", "Fonts/MarkerFelt", 22, CCLabelFormat.SpriteFont);
// add the label as a child to this Layer
AddChild(label);
}
protected override void AddedToScene()
{
base.AddedToScene();
// Use the bounds to layout the positioning of our drawable assets
var bounds = VisibleBoundsWorldspace;
// position the label on the center of the screen
label.Position = bounds.Center;
// Register for touch events
var touchListener = new CCEventListenerTouchAllAtOnce();
touchListener.OnTouchesEnded = OnTouchesEnded;
AddEventListener(touchListener, this);
}
void OnTouchesEnded(List<CCTouch> touches, CCEvent touchEvent)
{
if (touches.Count > 0)
{
// Perform touch handling here
}
}
}
I put a break point in the method thats called when the event ViewCreated is fired, the breakpoint is never hit. I tried creating the CCGameView first then then registering the eventhandler because I thought the event was firing before registering
CCGameView gameView = new CCGameView(this);
gameView.ViewCreated += LoadGame;
gameView = (CCGameView)FindViewById(Resource.Id.GameView);
then I tried calling the LoadGame method directly
CCGameView gameView = (CCGameView)FindViewById(Resource.Id.GameView);
gameView.ViewCreated += LoadGame;
LoadGame(gameView, EventArgs.Empty);
but this resulted in a null exception for the gameView.ContentManager.
My only other suspicion is the emulator itself, perhaps it needs something installed extra, however for a normal xamarin android project it works perfectly. Iv also tried looking at the various examples on Xamarin but they all use Application Delegate, which if i'm not mistaken, was the old way of doing thing. If anyone can help, Id appreciate it. Thanks
It was an emulator issue, had to check the Use Host GPU option on the emulator. On the Android Virtual Device Manager where I can select my created emulators, I selected an emulator I had created, then instead of starting it, I first Edited it, that's where I found the option (Since I had already created some emulators). The answer is here
Related
I am working on a project "CoManga" and I wanted to add advertisements in it. Implementing ads on UWP seemed straight forward, like Android and iOS. However, I'm stuck now.
Anyways, I followed this tutorial by James Montemagno and added everything. I even see the test advertisements, which is great. However, when I try to move away from that page (when I press "BACK Button") and go to previous page, I get an error.
This is the error :
Setting up AdControlView in UWP throws System.InvalidOperationException: 'Cannot assign a native control without an Element; Renderer unbound and/or disposed. Please consult Xamarin.Forms renderers for reference implementation of OnElementChanged.'.
It is thrown at line number 50, where I set the SetNativeControl(adView);. I've commented it out right now, but as soon as I un-comment it, I see this error.
Can someone help me out here with this.
Setting up AdControlView in UWP throws System.InvalidOperationException: 'Cannot assign a native control without an Element; Renderer unbound and/or disposed. Please consult Xamarin.Forms renderers for reference implementation of OnElementChanged.
The reason is that xamarin Element has released but SetNativeControl invoked again cause the native control can't find the matched xamarin Element when page going back. So you could set a flag (isRegist) to record the registed ad.
public class AdViewRenderer : ViewRenderer<AdControlView, AdControl>
{
string bannerId = "test";
AdControl adView;
string applicationID = "3f83fe91-d6be-434d-a0ae-7351c5a997f1";
bool isRegist = false;
protected override void OnElementChanged(ElementChangedEventArgs<AdControlView> e)
{
base.OnElementChanged(e);
if (Control == null && isRegist != true)
{
CreateNativeAdControl();
SetNativeControl(adView);
isRegist = true;
}
}
private void CreateNativeAdControl()
{
if (adView != null)
return;
var width = 300;
var height = 50;
if (AnalyticsInfo.VersionInfo.DeviceFamily == "Windows.Desktop")
{
width = 728;
height = 90;
}
// Setup your BannerView, review AdSizeCons class for more Ad sizes.
adView = new AdControl
{
ApplicationId = applicationID,
AdUnitId = bannerId,
HorizontalAlignment = Windows.UI.Xaml.HorizontalAlignment.Center,
VerticalAlignment = Windows.UI.Xaml.VerticalAlignment.Bottom,
Height = height,
Width = width
};
}
}
i have a problem when i navigate from a secondary tile into my app. The tile is created and has a navigation uri. Now i have a problem:
On "navigateTo" i test the navigationcontext for a specific string. If the string has the number i call this number. The first problem i have is when i navigate to an other page inside the app (after first click on secondary tile) and then return back to mainpage, it also tries to call the number, because the navigationcontext is the same as when i click the secondary tile.
If i clear the navigationcontext after the first click on secondary tile the navigation works. But if i pause the app and than click the secondary tile again the navigationcontext is empty and so no number is called.
Create of tile
IconicTileData tileData = new IconicTileData
{
Title = App.MainViewModel.SelectedPOI.Name,
SmallIconImage = new Uri("/Assets/Images/feature.phone.png", UriKind.Relative),
WideContent1 = App.MainViewModel.SelectedPOI.Name,
WideContent2 = App.MainViewModel.SelectedPOI.Telefonnumber,
WideContent3 = App.MainViewModel.SelectedPOI.Street
};
if (App.MainViewModel.SelectedPOI.Id == -1)
tileData.BackgroundColor = Helper.GetColorFromHexString("#E46D1D");
else
tileData.BackgroundColor = Helper.GetColorFromHexString("#4FAE32");
string SecondaryTileUriSource = String.Format("Source={0}&ID={1}", TILESTATUS, App.MainViewModel.SelectedPOI.Id);
//check if tile exist
ShellTile tile = Helper.FindTile(SecondaryTileUriSource);
if (tile == null)
{
// having a unique NavigationUri is necessary for distinguishing this tile
string tileUri = string.Concat("/MainPage.xaml?", SecondaryTileUriSource);
ShellTile.Create(new Uri(tileUri, UriKind.Relative), tileData, true);
}
OnNavigateTo - MainPage
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
string status = String.Empty;
if (NavigationContext.QueryString.TryGetValue("Source", out status))
{
MainPivot.SelectedItem = AlarmPivotItem;
//App.MainViewModel.StartAlarm();
//or
//get the number from source/status...
App.MainViewModel.CallNumber(12345);
//NavigationContext.QueryString.Clear();
}
}
Has anybody an example where e.g. a Number is called from a secondary tile and there are maybe at least 2 pages inside the app?
Any other sugestion where the problem can be?
Thank you
Rather than clearing the navigation context, you can use the NavigationMode property to know whether it's a new navigation to the page (for instance, form the secondary tile) or if the user went back from another page:
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
if (e.NavigationMode != System.Windows.Navigation.NavigationMode.Back)
{
if (NavigationContext.QueryString.TryGetValue("Source", out status))
{
MainPivot.SelectedItem = AlarmPivotItem;
//App.MainViewModel.StartAlarm();
//or
//get the number from source/status...
App.MainViewModel.CallNumber(12345);
}
}
}
Ok... So my problem is to prevent from activity to reload after orientation is changed.
Basically, what I did is this:
[Activity(Label = "migs", ConfigurationChanges = Android.Content.PM.ConfigChanges.Orientation)]
This is worked fine, until I changed "Target API" to 14. If I'm changing it back to 12, then everything is working, but on 14, activity is being restarted (OnCreate method is fires after rotation).
So... You'll ask why do I need "Target API" 14? - Easy! Because in my app, I'm playing video, and for that I need "true full screen". All API's below 14 adding "Settings" (three dots) button. In case of HTC, it's big and ugly button, that I was unable to get rid of.
If you know how to do one of the two (Get rid of the "settings" button in API 12, or prevent activity from reload after orientation changed in API 14), I'll be very thank full for your help.
Ok... At last I solved it! :)
Saving activity state instead of preventing activity from reload, from first sight can seem to be a little tricky, but in fact is really easy and it's the best solution for situations like this.
In my case, I had a ListView, that populates from the internet with items, that stored in custom list adapter. If device orientation was changed, the activity was reloaded, so does the ListView, and I was loosing all the data.
All I needed to do is to override the OnRetainNonConfigurationInstance method.
Here's a quick sample of how to do it.
First of all, we need a class, that can handle all of our stuff.
Here is a wrapper for all the things we need to save:
public class MainListAdapterWrapper : Java.Lang.Object
{
public Android.Widget.IListAdapter Adapter { get; set; }
public int Position { get; set; }
public List<YourObject> Items { get; set; }
}
In our activity, we need to hold variables, to store all the data:
ListView _listView; //Our ListView
List<YourObject> _yourObjectList; //Our items collection
MainListAdapterWrapper _listBackup; //The instance of the saving state wrapper
MainListAdapter _mListAdapter; //Adapter itself
Then, we overriding the OnRetainNonConfigurationInstance method in the activity:
public override Java.Lang.Object OnRetainNonConfigurationInstance()
{
base.OnRetainNonConfigurationInstance();
var adapterWrapper = new MainListAdapterWrapper();
adapterWrapper.Position = this._mListAdapter.CurrentPosition; //I'll explain later from where this came from
adapterWrapper.Adapter = this._listView.Adapter;
adapterWrapper.Items = this._yourObjectList;
return adapterWrapper;
}
And the final stage is to load saved state in OnCreate method:
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.list);
this._listView = FindViewById<ListView>(Resource.Id.listView);
if (LastNonConfigurationInstance != null)
{
this._listBackup = LastNonConfigurationInstance as MainListAdapterWrapper;
this._yourObjectList = this._listBackup.Items;
this._mListAdapter = this._listBackup.Adapter as MainListAdapter;
this._listView.Adapter = this._mListAdapter;
//Scrolling to the last position
if(this._listBackup.Position > 0)
this._listView.SetSelection(this._listBackup.Position);
}
else
{
this._listBackup = new MainListAdapterWrapper();
//Here is the regular loading routine
}
}
And about the this._mListAdapter.CurrentPosition... In my MainListAdapter, I added this property:
public int CurrentPosition { get; set; }
And the, in the `GetView' method, I did that:
this.CurrentPosition = position - 2;
P.S.
You don't have to implement exactly as I showed here. In this code, I'm holding a lot of variables, and making all the routine inside the OnCreate method - that is wrong. I did that, just to show how it can be implemented.
what happen when orientation change (consider you enable rotation in your phone) ?
Android restart activity onDestroy() is called, followed by onCreate() , you can distinguish between onDestroy() call to kill activity or restart app throw old answer.
Prevent Activity restart
just set ConfigurationChanges to both Orientation , ScreenSize
[Activity (Label = "CodeLayoutActivity", ConfigurationChanges=Android.Content.PM.ConfigChanges.Orientation | Android.Content.PM.ConfigChanges.ScreenSize)]
why this may be not working ?
I dont think this will not working but set RetaintInstance to true read more about RetainInstance
class myFragment: Fragment
{
public override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
this.RetainInstance = true;
// this to change screen orientation
Activity.RequestedOrientation = ScreenOrientation.Landscape;
}
.....
}
hope this help
Above API 13, you need to include screensize in your ConfigChanges.
As denoted here.
Maybe adding that tag to your activity for API13+ will help?
I have downloaded Kinect SDK 1.7, toolkit and have played with following samples.
ControlBasics WPF
InteractionGallery WPF.
I figured out that Kinect Toolkit internally uses the interaction frame to detect the hand position/gesture and accordingly maps it with the Kinect Controls.
I have a requirement where I want to capture a grip event on a Kinect Tile Button. Since the default KinectTileButton does not provide a Grip event. I added a grip event handler on my button.
KinectRegion.AddHandPointerGripHandler(kinectButton, OnHandPointerCaptured);
private void OnHandPointerCaptured(object sender, HandPointerEventArgs handPointerEventArgs)
{
// Add code here
}
I placed a debug breakpoint inside the OnHandPointerCaptured method and was able to receive proper hits when I grip on the KinectTileButton. But for some reason I do not see the KinectCursor image change to a grip as it happens on the KinectScrollViewer control.
I tried setting up the isGripTarget property in the KinectButtonBase class but it doesn't help.
private void InitializeKinectButtonBase()
{
KinectRegion.AddHandPointerPressHandler(this, this.OnHandPointerPress);
KinectRegion.AddHandPointerGotCaptureHandler(this, this.OnHandPointerCaptured);
KinectRegion.AddHandPointerPressReleaseHandler(this, this.OnHandPointerPressRelease);
KinectRegion.AddHandPointerLostCaptureHandler(this, this.OnHandPointerLostCapture);
KinectRegion.AddHandPointerEnterHandler(this, this.OnHandPointerEnter);
KinectRegion.AddHandPointerLeaveHandler(this, this.OnHandPointerLeave);
// Use the same OnHandPointerPress handler for the grip event
KinectRegion.AddHandPointerGripHandler(this, this.OnHandPointerPress);
//Set Kinect button as Grip target
// KinectRegion.SetIsPressTarget(this, true);
KinectRegion.SetIsGripTarget(this, true);
}
How do I change the KinectCursor image from openhand icon to grip, and also the size.
Here's what i found-
1) Cursor Image and Size - Both these samples use Microsoft.Kinect.Toolkit.Controls project that defines the Custom Controls (KinectTileButton,KinectScrollViwer,KinectRegion etc.) used in these samples. The Kinect Cursor image and size is defined as a resource in
Microsoft.Kinect.Toolkit.Controls ->Themes->Generic.xaml. Search for following in the file -
<Style TargetType="{x:Type local:KinectCursor}">
You can modify this as per your need. Wasn't able to find any properties/hooks exposed to control this directly from the UI.
2) Grip event on Tile Button - Kinect Button Supports various events which can be subsribed to and acted upon on your desire. see this
Hand over button event in Kinect SDK 1.7
3) Change Cursor image to Grip on Tile Button -
Microsoft.Kinect.Toolkit.Controls project uses KinectCursorVisualizer.cs and KinectCursor.cs to render the virtual hand cursor on the UI. The Open Hand/Grip visual state is controlled via this Dependency Property defined in KinectCursor.cs.
public static readonly DependencyProperty IsOpenProperty = DependencyProperty.Register(
"IsOpen",
typeof(bool),
typeof(KinectCursor),
new UIPropertyMetadata(true, (o, args) => ((KinectCursor)o).EnsureVisualState()));
A quick find all references on the property IsOpen tells that the only place where this property is set is in KinectCursorVisualizer.cs-> OnHandPointersUpdated method. Line- 229
// Set open state
cursor.IsOpen = !pointer.IsInGripInteraction;
And this pointer.IsInGripInteraction property is set at KinectAdapter.cs Line 678
handPointer.IsInGripInteraction = newIsInGripInteraction;
If you look at the code just above this line you'll find that this property is only set to true if the target element has a QueryInteractionStatusHandler defined and it sets
args.Handled , args.IsInGripInteraction property to true.
Since KinectScrollViewer has this handler defined you see a grip image.
private void InitializeKinectScrollViewer()
{
KinectRegion.AddHandPointerGotCaptureHandler(this, this.OnHandPointerCaptured);
KinectRegion.AddHandPointerLostCaptureHandler(this, this.OnHandPointerLostCapture);
KinectRegion.AddHandPointerEnterHandler(this, this.OnHandPointerEnter);
KinectRegion.AddHandPointerMoveHandler(this, this.OnHandPointerMove);
KinectRegion.AddHandPointerPressHandler(this, this.OnHandPointerPress);
KinectRegion.AddHandPointerGripHandler(this, this.OnHandPointerGrip);
KinectRegion.AddHandPointerGripReleaseHandler(this, this.OnHandPointerGripRelease);
//This is the QueryInteractionStatusHandler
KinectRegion.AddQueryInteractionStatusHandler(this, this.OnQueryInteractionStatus);
KinectRegion.SetIsGripTarget(this, true);
this.scrollMoveTimer.Tick += this.OnScrollMoveTimerTick;
this.scrollViewerInertiaScroller.SlowEnoughForSelectionChanged += this.OnSlowEnoughForSelectionChanged;
// Create KinectRegion binding
this.kinectRegionBinder = new KinectRegionBinder(this);
this.kinectRegionBinder.OnKinectRegionChanged += this.OnKinectRegionChanged;
}
but KinectTileButton (extends KinectButtonBase) does not have this handler defined
private void InitializeKinectButtonBase()
{
KinectRegion.AddHandPointerPressHandler(this, this.OnHandPointerPress);
KinectRegion.AddHandPointerGotCaptureHandler(this, this.OnHandPointerCaptured);
KinectRegion.AddHandPointerPressReleaseHandler(this, this.OnHandPointerPressRelease);
KinectRegion.AddHandPointerLostCaptureHandler(this, this.OnHandPointerLostCapture);
KinectRegion.AddHandPointerEnterHandler(this, this.OnHandPointerEnter);
KinectRegion.AddHandPointerLeaveHandler(this, this.OnHandPointerLeave);
KinectRegion.SetIsPressTarget(this, true);
}
How to define this handler ? - Simple add following to your UI. Can be added to constructor
//Add the handler
KinectRegion.AddQueryInteractionStatusHandler(kinectButton, OnQuery);
Define the Handler
//Variable to track GripInterationStatus
bool isGripinInteraction = false;
private void OnQuery(object sender, QueryInteractionStatusEventArgs handPointerEventArgs)
{
//If a grip detected change the cursor image to grip
if (handPointerEventArgs.HandPointer.HandEventType == HandEventType.Grip)
{
isGripinInteraction = true;
handPointerEventArgs.IsInGripInteraction = true;
}
//If Grip Release detected change the cursor image to open
else if (handPointerEventArgs.HandPointer.HandEventType == HandEventType.GripRelease)
{
isGripinInteraction = false;
handPointerEventArgs.IsInGripInteraction = false;
}
//If no change in state do not change the cursor
else if (handPointerEventArgs.HandPointer.HandEventType == HandEventType.None)
{
handPointerEventArgs.IsInGripInteraction = isGripinInteraction;
}
handPointerEventArgs.Handled = true;
}
You may have to tweak this as per your requirement. Happy Kinecting :)
My setting:
I've got a C# application (.NET 3.5) in Visual Studio 2008. No chance to switch to WPF or whatsoever :).
My app contains a custom control (a button class derived from Windows.Forms.Button) that acts as a replacement for the Windows.Forms.TabControl. I can associate these buttons with one another and each button can be associated with one control that it is dealing with (usually some sort of Windows.Forms.Panel). It looks something like this:
public class TabButton : System.Windows.Forms.Button
{
// ...
protected override void OnClick(EventArgs e)
{
base.OnClick(e);
this.myAssociatedControl.Visible = true;
this.tellMyBuddiesToHideTheirControls();
}
// ...
}
Basically it is just about clicking a button, showing its bound control and having the controls bound to the associated buttons disappear - just like the TabControl, but the approach is easily designable and I can place the buttons far from their content panels.
The problem:
This works pretty well at runtime, but the usage at design time is arguably odd: With the mouse, find a control that´s belonging to the group and run a series of <Send To Back>s until the desired control is visible.
The question:
Is there a way to tell the VS designer to evaluate the clicks on the buttons at design time like it does with the TabControl so that I can switch the tabs just by clicking them like I would at runtime?
I've been searching for quite a while now. There are some articles here at SO but they only seem to cover adding additional attributes to the properties designer.
Edith says:
By request, an answer to my own question ...
This is the solution that is suitable to my application. It is basically an example from the msdn with some twists to get the custom designer to use a callback on click. Hope it helps anyone :-).
[System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")]
public class TabButtonDesigner : System.Windows.Forms.Design.ControlDesigner
{
ShowTabGlyph myGlyph = null;
Adorner myAdorner;
public TabButtonDesigner()
{
}
public override void Initialize(IComponent component)
{
base.Initialize(component);
// Add the custom set of glyphs using the BehaviorService.
// Glyphs live on adornders.
myAdorner = new Adorner();
BehaviorService.Adorners.Add(myAdorner);
myGlyph = new ShowTabGlyph(BehaviorService, Control);
myGlyph.Callback = () =>
{
((MyCustomTabButton)this.Control).ShowMyTab();
};
myAdorner.Glyphs.Add(myGlyph);
}
class ShowTabGlyph : Glyph
{
Control control;
BehaviorService behaviorSvc;
public Action Callback
{
get;
set;
}
public ShowTabGlyph(BehaviorService behaviorSvc, Control control) :
base(new ShowTabBehavior())
{
this.behaviorSvc = behaviorSvc;
this.control = control;
}
public override Rectangle Bounds
{
get
{
// Create a glyph that is 10x10 and sitting
// in the middle of the control. Glyph coordinates
// are in adorner window coordinates, so we must map
// using the behavior service.
Point edge = behaviorSvc.ControlToAdornerWindow(control);
Size size = control.Size;
Point center = new Point(edge.X + (size.Width / 2),
edge.Y + (size.Height / 2));
Rectangle bounds = new Rectangle(
center.X - 5,
center.Y - 5,
10,
10);
return bounds;
}
}
public override Cursor GetHitTest(Point p)
{
// GetHitTest is called to see if the point is
// within this glyph. This gives us a chance to decide
// what cursor to show. Returning null from here means
// the mouse pointer is not currently inside of the glyph.
// Returning a valid cursor here indicates the pointer is
// inside the glyph, and also enables our Behavior property
// as the active behavior.
if (Bounds.Contains(p))
{
return Cursors.Hand;
}
return null;
}
public override void Paint(PaintEventArgs pe)
{
// Draw our glyph. It is simply a blue ellipse.
pe.Graphics.DrawEllipse(Pens.Blue, Bounds);
}
// By providing our own behavior we can do something interesting
// when the user clicks or manipulates our glyph.
class ShowTabBehavior : Behavior
{
public override bool OnMouseUp(Glyph g, MouseButtons button)
{
//MessageBox.Show("Hey, you clicked the mouse here");
//this.
ShowTabGlyph myG = (ShowTabGlyph)g;
if (myG.Callback != null)
{
myG.Callback();
}
return true; // indicating we processed this event.
}
}
}
}
[DesignerAttribute(typeof(TabButtonDesigner))]
public class MyCustomTabButton : System.Windows.Forms.Button
{
// The attribute will assign the custom designer to the TabButton
// and after a rebuild the button contains a centered blue circle
// that acts at design time like the button in runtime does ...
// ...
}