I have a requirement to rotate the screen to Landscape from Portrait. Then I should stay in Landscape even though I have not tilted my phone. Portrait and Landscape have different views with buttons for orientation change and is in same content page which I have handled with content template. So, now I wanted to rotate automatically if I tilt the phone or if I tap on the button in either view to change orientation.
Portrait -> Landscape change using button then I should stay in landscape view until one rotation happen.
ex:- Now, I came to Landscape using a sensor, and I am in Landscape mode if I tap the button for rotation then I should change in portrait and should stay there.
I want to satisfy both cases. How to achieve that in Android and iOS (Xamarin.Forms)?
Anyone faces this kind of usecase and if you got a solution. Help me out.
When using Xamarin.Forms, the supported method of controlling device orientation is to use the settings for each individual project.
You could call the following method in dependency service.
Create a interface:
public interface IOrientationService
{
void Landscape();
void Portrait();
}
Android:
public class OrientationService : IOrientationService
{
public void Landscape()
{
((Activity)Forms.Context).RequestedOrientation = ScreenOrientation.Landscape;
}
public void Portrait()
{
((Activity)Forms.Context).RequestedOrientation = ScreenOrientation.Portrait;
}
}
iOS:
public class OrientationService : IOrientationService
{
public void Landscape()
{
AppDelegate appDelegate = (AppDelegate)UIApplication.SharedApplication.Delegate;
appDelegate.allowRotation = true;
UIDevice.CurrentDevice.SetValueForKey(new NSNumber((int)UIInterfaceOrientation.LandscapeLeft), new NSString("orientation"));
}
public void Portrait()
{
AppDelegate appDelegate = (AppDelegate)UIApplication.SharedApplication.Delegate;
appDelegate.allowRotation = true;
UIDevice.CurrentDevice.SetValueForKey(new NSNumber((int)UIInterfaceOrientation.Portrait), new NSString("orientation"));
}
}
For the usage of dependency service, you could refer to the link below. How can I block rotation to only allow portrait mode in xamarin forms?
I want to rotate only one page in my app automatically and as well as manually.
When you do the navigation, you could do the Orientation before loading the page in OnAppearing event.
protected override void OnAppearing()
{
base.OnAppearing();
DependencyService.Get<IOrientationService>().Landscape();
}
Both portrait and landscape views are different.
Liek 1., you could set the Orientation you want to in each page with OnAppearing() event.
I should not lock the particular page at any cause but I also when I want to change orientation manually I should able to do that. Even though I am not rotating/tilt the phone.
If you want to do it manually, invoke the Landscape or Portrait in a click event or tap or something else.
Currently, i'm trying to work with augment reality in android. For this task i'm using Unity + Vuforia.
So, i have made a scene, which is working, when i'm looking to specific object from my camera it shows me my model(basically 3d cat model with animation). I've done this according to tutorials like this:
text format tutorial and videos on youtube like this : video tutroial.
After this i've made android application, based on this scene, like this:
The result is Android project, which basically has one Activity and banch of assets and libs. The only connection with Unity that i see so far is UnityPlayer class, but it's just a ViewGroup, extended from FrameLayout
public class UnityPlayer extends FrameLayout implements com.unity3d.player.a.a
My goal: I need to overrideonClick on the view from Unity, which i've created(my 3d cat), something like when you click on cat on your phone, it will make some sound, and set some animation to it on after clicking. I have a model on the scene, just logically it has been converted to View class inside of Android, and i thought that it's just a child of UnityPlayer, but code like this :
mUnityPlayer.getChildAt(0).setOnClickListener
has no effect.
I want either have some object which will contain all the animations and other properties which model in unity has, or if it's impossible, learn how to set onClick listeners in Unity itself
I realize that this question might be unclear, and i would like to explain it in more details for those who would try to help.
If you need more info, just ask for it in comments. Thanks
Edit: As answer was suggesting, i could simply write a script for this, which i did, for using VirtualButton, it looks like this:
using UnityEngine;
using System.Collections.Generic;
using Vuforia;
public class VirtualButtonEventHandler : MonoBehaviour, IVirtualButtonEventHandler {
// Private fields to store the models
private GameObject kitten;
private GameObject btn;
/// Called when the scene is loaded
void Start() {
// Search for all Children from this ImageTarget with type VirtualButtonBehaviour
VirtualButtonBehaviour[] vbs = GetComponentsInChildren<VirtualButtonBehaviour>();
for (int i = 0; i < vbs.Length; ++i) {
// Register with the virtual buttons TrackableBehaviour
vbs[i].RegisterEventHandler(this);
}
// Find the models based on the names in the Hierarchy
kitten = transform.FindChild("kitten").gameObject;
btn = transform.FindChild("btn").gameObject;
kitten.SetActive(false);
btn.SetActive(true);
}
/// <summary>
/// Called when the virtual button has just been pressed:
/// </summary>
public void OnButtonPressed(VirtualButtonAbstractBehaviour vb) {
//Debug.Log(vb.VirtualButtonName);
//GUI.Label(new Rect(0, 0, 10, 5), "Hello World!");
}
/// Called when the virtual button has just been released:
public void OnButtonReleased(VirtualButtonAbstractBehaviour vb) {
}
}
As you can see, in Start() method i want to find and hide model, which called kitten, but it's not hiding
I've attached this script to virtual button object, i will provide a screen:
Edit: My mistake actually, for some reason, i had to attach VirtualButtonBehaviorHandler script to an ImageTarget, it's not that simple to understand for me, but i think i see some logic behind it right now.
But, for some unknow reason, if i'm adding this code:
public void OnButtonPressed(VirtualButtonAbstractBehaviour vb) {
//Debug.Log(vb.VirtualButtonName);
switch(vb.VirtualButtonName) {
case "btn":
kitten.setActive(true);
break;
}
}
It works instantly, even without touching on the button
Final edit: This was happenning, because i've add my button in database .xml, when i've removed button from it - everything worked, i'm marking the only one answer as correct, because it helped me
Brother Everything is possible if we do it. As per my understanding , what exactly you want to do is :
First : You need to clear some basic concept by reading blog & Tutorials:
As you mentioned object on which your white cyte :) cat render is "Marker"
In Unity Everything is gameobject you can write script to manipulate that gameobject (CAT) using script. which will be in either C#(Mono) or JavaScript for this work you can use Visual Studio or MonoDevelop by Unity
But before that please search for keywords on google
a) Touchevent, RayCastMenu Controle in unity: To handle Touch
b) MonoBehaviour class, Start() , Update(), OnGUI() method in Unity
You can identify any gameObject by using its name or Tag which you can see or change in Inspector window
These are some basic things . Please follow vuforia developer portal to learn more:
https://developer.vuforia.com/library/
Now: Coming to your question:
According to me you wanna do some stuff on Click of your sweet cat .
Its simple, if simply you want to launch android activity on click of cat then there are 2 possible ways:
Create android project and import it in unity as Library project in Unity.
OR
create android activity from unity project with the help of C# script. Attach this script to any GameObject in scene.
Here I providing the example of second one : On click of Button It will launch Android Activity.
What you have to do is:
Replace Button GameObject By CAT GameObjectExport Project as Android and write activity with same name and package as mention in C# code to do whatever you want to
Here In my example I have explained:
How to popup GUI when Marker is detected using Unity+ Vuforia
How to launch android Activity from Unity Code on Specific event
How to handle Event in Unity
How to maintain GUI same with multiple Resolutions
Please Study code Carefully and read the comments also :)
using UnityEngine;
using System.Collections;
using Vuforia; //import Vuforia
using System;
public class ButtonPopup : MonoBehaviour, ITrackableEventHandler
{
float native_width= 1920f;// Native Resolution to maintain resolution on different screen size
float native_height= 1080f;
public Texture btntexture;// drag and drop any texture in inspector window
private TrackableBehaviour mTrackableBehaviour;
private bool mShowGUIButton = false;
void Start () {
mTrackableBehaviour = GetComponent<TrackableBehaviour>();
if (mTrackableBehaviour) {
mTrackableBehaviour.RegisterTrackableEventHandler(this);
}
}
public void OnTrackableStateChanged(
TrackableBehaviour.Status previousStatus,
TrackableBehaviour.Status newStatus)
{
if (newStatus == TrackableBehaviour.Status.DETECTED ||
newStatus == TrackableBehaviour.Status.TRACKED ||
newStatus == TrackableBehaviour.Status.EXTENDED_TRACKED)
{
mShowGUIButton = true;// Button Shown only when marker detected same as your cat
}
else
{
mShowGUIButton = false;
}
}
void OnGUI() {
//set up scaling
float rx = Screen.width / native_width;
float ry = Screen.height / native_height;
GUI.matrix = Matrix4x4.TRS (new Vector3(0, 0, 0), Quaternion.identity, new Vector3 (rx, ry, 1));
Rect mButtonRect = new Rect(1920-215,5,210,110);
if (!btntexture) // This is the button that triggers AR and UI camera On/Off
{
Debug.LogError("Please assign a texture on the inspector");
return;
}
if (mShowGUIButton) {
// different screen position for your reference
//GUI.Box (new Rect (0,0,100,50), "Top-left");
//GUI.Box (new Rect (1920 - 100,0,100,50), "Top-right");
//GUI.Box (new Rect (0,1080- 50,100,50), "Bottom-left");
//GUI.Box (new Rect (Screen.width - 100,Screen.height - 50,100,50), "Bottom right");
// draw the GUI button
if (GUI.Button(mButtonRect, btntexture)) {
// do something on button click
OpenVideoActivity();
}
}
}
public void OpenVideoActivity()
{
var androidJC = new AndroidJavaClass("com.unity3d.player.UnityPlayer”);// any package name maintain same in android studio
var jo = androidJC.GetStatic<AndroidJavaObject>("currentActivity");
// Accessing the class to call a static method on it
var jc = new AndroidJavaClass("com.mobiliya.gepoc.StartVideoActivity”);//Name of android activity
// Calling a Call method to which the current activity is passed
jc.CallStatic("Call", jo);
}
}
Remember : In Unity everything is GameObject and you can write script to manipulate any GameObject
Edit: Info for Virtual Button
Virtual Buttons detect when underlying features of the target image are obscured from the camera view. You will need to place your button over an area of the image that is rich in features in order for it to reliably fire its OnButtonPressed event. To determine where these features are in your image, use the Show Features link for your image in the Target Manager.
Choose areas in the images that have dimensions of approximately 10% of the image target’s size.
Here is example in image i have simplify for you:
Register the Virtual Button:
To add a virtual button to an image target, add the VirtualButton element and its attributes to the ImageTarget element in the .xml file.
XML Attributes:
Name - a unique name for the button
Rectangle - defined by the four corners of the rectangle in the
target's coordinate space
Enabled - a boolean indicating whether the button should be enabled
by default
Sensitivity - HIGH, MEDIUM, LOW sensitivity to occlusion
You can get .Xml file in streamingAsset folder in unity project .
<ImageTarget size="247 173" name="wood">
<VirtualButton name="red" sensitivity="HIGH" rectangle="-108.68 -53.52 -75.75 -65.87"
enabled="true" />
<VirtualButton name="blue" sensitivity="LOW" rectangle="-45.28 -53.52 -12.35 -65.87"
enabled="true" />
<VirtualButton name="yellow" sensitivity="MEDIUM" rectangle="14.82 -53.52 47.75 -65.87"
enabled="true" />
<VirtualButton name="green" rectangle="76.57 -53.52 109.50 -65.87"
enabled="true" />
</ImageTarget>
After Registering Virtual Button Code is simple then:
public class Custom_VirtualButton : MonoBehaviour, IVirtualButtonEventHandler
{
// Use this for initialization
void Start () {
// here it finds any VirtualButton Attached to the ImageTarget and register it's event handler and in the
//OnButtonPressed and OnButtonReleased methods you can handle different buttons Click state
//via "vb.VirtualButtonName" variable and do some really awesome stuff with it.
VirtualButtonBehaviour[] vbs = GetComponentsInChildren<VirtualButtonBehaviour>();
foreach (VirtualButtonBehaviour item in vbs)
{
item.RegisterEventHandler(this);
}
}
// Update is called once per frame
void Update () {
}
#region VirtualButton
public void OnButtonPressed(VirtualButtonAbstractBehaviour vb)
{
Debug.Log("Helllllloooooooooo");
}
public void OnButtonReleased(VirtualButtonAbstractBehaviour vb)
{
Debug.Log("Goooooodbyeeee");
}
#endregion //VirtualButton
}
and after writing this code you have to go to StreamingAsset/QCAR and find your ImageTarget XML Association & do something like this:
<?xml version="1.0" encoding="UTF-8"?>
<QCARConfig xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="qcar_config.xsd">
<Tracking>
<ImageTarget name="marker01" size="100.000000 100.000000">
<VirtualButton name="red" rectangle="-49.00 -9.80 -18.82 -40.07" enabled="true" />
</ImageTarget>
</Tracking>
</QCARConfig>
Best of Luck :) Bdw CAT is so cute:)
We are developing an Android application where the requirement is to have single image having different navigation when the different parts of the image are clicked. E.g. A full image of a building and clicking on the different flats we want to show the amenities offered in the flat ( build up area, number of rooms, number of balconies, terrace (if pent house) etc).
Have thought the following two possibilities,
Slice the images and put together (such that it look as a single image) in layout xml, once user clicks it, with the image view id we will know which portion is clicked.
Slice the images and put together (such that it look as a single image) in html with onclick event, load the html in webview, create JavaScript class that handles clicks.
With above two it is difficult because the parts are not proper rectangle or square shaped.
ASP.Net has ImageMap control for this purpose, do we have anything of that sort in Android?
There is no such component to do this in android, but you can easily create one:
public class ImageMap extends ImageView implements onClickListener
{
List<Rect> hotspot;
public ImageMap(Context c)
{
super(c);
hotspot = new List<Rect>();
setOnClickListener(this);
}
public void addHotSpot(Rect r)
{
hotspots.add(r);
}
public void onClick(Event e)
{
int currentPosition = 0;
for(Rect spot : hotspot){
if(spot.contains(e.getX(), e.getY()))
triggerClickInHotSpotAtPos(currentPosition);
currentPosition ++;
}
}
public void triggerHotSpot(int hotspotIndex)
{
//TODO do something useful like calling listener for this given hotspot etc ...
}
}
be aware that is not a finished work, but its more like pseudo code, the important is you got the idea.
You could do this with a single ImageView by tapping into its onTouch event handler.
See the MotionEvent documentation for specifics on how to get coordinates of the touch event.
I'm thinking of integrating Leadbolt (or Tapjoy) to my Libgdx game. I want to make a store based on the clicked forms. More click - more stuff from the store for the user. I found Leadbolt and Tapjoy. These ad providers are providing direct helps for these stuffs. I have take a look on the Leadbolt integrating guide. I have a problem with it. It needs me to pass a context to the AdController. I don't know if it possible in any way to pass the context for the AdController or not, so I would like to ask you about it, that how can I do, if I can. (I haven't tried it in Libgdx yet, but with the superjumper example had problem too, when I wanted to pass a context for something, and I think because the Libgdx app don't extends an Activity, it will have problems too.)
Here is the sample code from Leadbolt:
AdController myControllerForm = new AdController(this, "MY_LB_ID", new AdListener() {
public void onAdProgress() {}
public void onAdLoaded() {
myControllerForm.hideAd();
}
public void onAdFailed() {
launchMain();
}
public void onAdCompleted() {
myControllerForm.hideAd();
launchMain();
}
public void onAdClosed() {
launchMain();
}
public void onAdClicked() {}
public void onAdAlreadyCompleted() {
launchMain();
}
public void onAdHidden() {
launchMain();
}
});
myControllerForm.setAsynchTask(true);
myControllerForm.loadAd();
}
public void launchMain()
{
finish();
startActivity(new Intent(Splash.this, MainApp.class));
}
}
The class extends Activity, and the methods are in the onCreate() method in this example.
If you have integrated the Leadbolt or Tapjoy to your Libgdx game, then could you please give me a code about how did you do it?
Thanks in advance!
LibGDX actually extends AndroidActivity (by AndroidApplication, which extends AndroidActivity).
If you setup your project correctly, you can access it from "Android starter" project. This is also the only place, where you can play with ads, because "Desktop starter" in no way extends AndroidActivity.
Here's also adMob tutorial, which you may find useful (creating overlaying views).
This is all info I can give you, as I don't know whether you want to display your ads always, reload them as time passes or just hide them after particular events. In such cases, you might want to implement your custom interfaces.
Good luck!
Check out the libGDX tutorial on AdMob: http://code.google.com/p/libgdx/wiki/AdMobInLibgdx
Skip the stuff at the top about setting up AdMob, I think you need the part in the "Control" section which talks about getting events from your generic libGDX code (which has to also run on the desktop) into your Android-specific code (for example to show an ad). The general way is to define your own interface (see the IActivityRequestHandler in the AdMob tutorial), and pass an object that implements that interface into your libGDX code. On the desktop this object would do nothing, and on the Android side you can use all the standard Android code to do the right thing.
I am making an app that has a scrolling screen like the homescreen style. I have implemented this solution:
Android Homescreen
It works great but I also want there to be buttons on each page that you can click to go to the next page but I just can't figure out how to do it! can someone help? I've been staring at this code for days now!
Thanks
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
UPDATE - HELP
I really don't understand how to get around the problem of calling the SetToScreen from the other activity, Can anyone help as if I try I do keep getting Static call errors.
Look at
public void setToScreen(int whichScreen) {}
Use this function to set to a screen on a click.
you should extend Draggablespace by adding a function to get the current space like:
public int getCurrentScreen() {
return this.mCurrentScreen;
}
then you can write your own functions in your activity like
public void nextScreen() {
draggableSpace.setToScreen(draggableSpace.getCurrentScreen() + 1));
}
The same for previous screen.
Now you only need to check if there is an additional screen waiting if you are going forward or backward.
(Of course draggableSpace is your object of the class draggablespace...not a static call!)