Implementing AdMob into my iOS libgdx game? - ios

It is to my understanding that the way to do what I am describing above is to add the following lines of code into the gradle
project(":ios") {
apply plugin: "java"
apply plugin: "robovm"
dependencies {
compile project(":core")
//...
compile "org.robovm:robopods-google-mobile-ads-ios:1.6.0"
}
}
However after doing this, Im lost as to what the next step is.. Im expecting something similar to what I have done to make it work with the android devices. However I cant seem to find the right information for this, any help would be very much appreciated on what the next step for me should be

After you add that line, right click your iOS project and Gradle>Refresh all.
You now have the robopods jar in your grade dependencies.
For your iOSLauncher.java:
package com.YOURPACKAGENAME;//TODO
import org.robovm.apple.coregraphics.CGRect;
import org.robovm.apple.coregraphics.CGSize;
import org.robovm.apple.foundation.Foundation;
import org.robovm.apple.foundation.NSAutoreleasePool;
import org.robovm.apple.uikit.UIApplication;
import org.robovm.apple.uikit.UIApplicationLaunchOptions;
import org.robovm.apple.uikit.UIScreen;
import org.robovm.pods.google.mobileads.GADAdSize;
import org.robovm.pods.google.mobileads.GADBannerView;
import org.robovm.pods.google.mobileads.GADRequest;
import com.badlogic.gdx.backends.iosrobovm.IOSApplication;
import com.badlogic.gdx.backends.iosrobovm.IOSApplicationConfiguration;
import com.YOURPACKAGENAME.GAMECLASS;//TODO
import com.badlogic.gdx.Application;
import com.badlogic.gdx.utils.Logger;
import org.robovm.pods.google.mobileads.GADBannerViewDelegateAdapter;
import org.robovm.pods.google.mobileads.GADRequestError;
public class IOSLauncher extends IOSApplication.Delegate {
private static CGSize AD_SIZE;
private static final Logger log = new Logger(IOSLauncher.class.getName(), Application.LOG_DEBUG);
private GADBannerView adview;
private boolean adsInitialized = false;
private IOSApplication iosApplication;
#Override
protected IOSApplication createApplication() {
GAMECLASS app = new GAMECLASS();//TODO
IOSApplicationConfiguration config = new IOSApplicationConfiguration();
config.orientationLandscape = false;
config.orientationPortrait = true;
iosApplication = new IOSApplication(app, config);
return iosApplication;
}
public static void main(String[] argv) {
NSAutoreleasePool pool = new NSAutoreleasePool();
UIApplication.main(argv, null, IOSLauncher.class);
pool.close();
}
// Ads
public void showAd() {
initializeAds();
//Portrait bottom screen
final CGSize screenSize = UIScreen.getMainScreen().getBounds().getSize();
double screenWidth = screenSize.getWidth();
AD_SIZE = adview.getBounds().getSize();
double adWidth = AD_SIZE.getWidth();
double adHeight = AD_SIZE.getHeight();
float bannerWidth = (float) screenWidth;
float bannerHeight = (float) (bannerWidth / adWidth * adHeight);
double screenHeight = screenSize.getHeight();
double adX = (screenWidth / 2) - (adWidth / 2);
double adY = screenHeight - bannerHeight;
//Landscape top screen
//<string>UIInterfaceOrientationLandscapeRight</string>
//<string>UIInterfaceOrientationLandscapeLeft</string>
/*
double adWidth = adSize.getWidth();
double adHeight = adSize.getHeight();
double screenHeight = screenSize.getHeight();
double screenWidth = screenSize.getWidth();
float bannerWidth = (float) screenWidth/2;
float bannerHeight = (float) ((float) screenHeight/10.0);
double adX = (screenWidth / 2) - (adWidth / 2);
double adY = 0;
*/
adview.setFrame(new CGRect(adX, adY, bannerWidth, bannerHeight));
}
#Override
public boolean didFinishLaunching (UIApplication application, UIApplicationLaunchOptions launchOptions) {
boolean didFinish = super.didFinishLaunching(application, launchOptions);
this.showAd();
return didFinish;
}
public void initializeAds() {
if (!adsInitialized) {
Foundation.log("Initalizing ads...");
adsInitialized = true;
adview = new GADBannerView(GADAdSize.SmartBannerPortrait());
adview.setAdUnitID("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); //put your secret key here TODO
adview.setRootViewController(iosApplication.getUIViewController());
iosApplication.getUIViewController().getView().addSubview(adview);
final GADRequest request = new GADRequest();
adview.setDelegate(new GADBannerViewDelegateAdapter() {
#Override
public void didReceiveAd(GADBannerView view) {
super.didReceiveAd(view);
log.debug("didReceiveAd");
}
#Override
public void didFailToReceiveAd(GADBannerView view,
GADRequestError error) {
super.didFailToReceiveAd(view, error);
//log.debug("didFailToReceiveAd:" + error);
Foundation.log("ERROR at didFailToReceiveAd: " + error);
}
});
adview.loadRequest(request);
Foundation.log("Initalizing ads complete.");
}
}
}
Should work for iOS 9.
Also if you have any problems running that, make sure you clean the roboVM cache after the latest updates.

Related

how to perform vertical swipe in android for appium

I am using Appium 1.7 and Android 8 on real device. But I am stuck with swipe up. tried with different combinations. Could you please provide an easy code for swipe functionality?
Tried:
private void scrollDown() {
//if pressX was zero it didn't work for me
int pressX = driver.manage().window().getSize().width / 2;
// 4/5 of the screen as the bottom finger-press point
int bottomY = driver.manage().window().getSize().height * 4/5;
// just non zero point, as it didn't scroll to zero normally
int topY = driver.manage().window().getSize().height / 8;
//scroll with TouchAction by itself
scroll(pressX, bottomY, pressX, topY);
}
/*
* don't forget that it's "natural scroll" where
* fromY is the point where you press the and toY where you release it
*/
private void scroll(int fromX, int fromY, int toX, int toY) {
TouchAction touchAction = new TouchAction(driver);
touchAction.longPress(fromX, fromY).moveTo(toX, toY).release().perform();
}
But no luck..!!
private void scroll(int fromX, int fromY, int toX, int toY) {
TouchAction touchAction = new TouchAction(driver);
touchAction.tap(fromX, fromY).waitAction(1000).moveTo(toX,
toY).release().perform();
}
you have to wait after pressing.
This will work
Can use this to swipe in any direction from point a to point b
This gives me the solution:
TouchAction action = new TouchAction(driver);
action.longPress(bottomElement).moveTo(topElement).release().perform();
According to this question: Appium - Java, How to automate swipe in android, the use of coordinates is Deprecated. I posted an answer there with the code that works for me in this case
You can perform scroll / swipe up action with below code:
Dimension size = this.driver.manage ()
.window ()
.getSize ();
int startX = size.getWidth () / 2;
int startY = size.getHeight () / 2;
int endX = 0;
int endY = (int) (startY * -1 * 0.75);
TouchAction action = new TouchAction (this.driver);
action.press (startX, startY)
.moveTo (endX, endY)
.release ()
.perform ();
You can tweak the code to perform left, down and right swipe. Let me know if this works for you.
i have used the below code to Swipe / Scroll and it is working perfectly
Code to Swipe UP
public boolean swipeFromUpToBottom()
{
try {
JavascriptExecutor js = (JavascriptExecutor) driver;
HashMap<String, String> scrollObject = new HashMap<String, String>();
scrollObject.put("direction", "up");
js.executeScript("mobile: scroll", scrollObject);
System.out.println("Swipe up was Successfully done.");
}
catch (Exception e)
{
System.out.println("swipe up was not successfull");
}
return false;
}
Code to Swipe DOWN
public boolean swipeFromBottomToUp()
{
try {
JavascriptExecutor js = (JavascriptExecutor) driver;
HashMap<String, String> scrollObject = new HashMap<String,String>);
scrollObject.put("direction", "down");
js.executeScript("mobile: scroll", scrollObject);
System.out.println("Swipe down was Successfully done");
}
catch (Exception e)
{
System.out.println("swipe down was not successfull");
}
return false;
}
Code for carousel images swipe
public boolean swipeImages()
{
try {
WebElement pageIndicator = driver.findElement(page_indicator);
String pageString= pageIndicator.getAttribute("value");
int length = pageString.length();
String count_string= pageString.substring(length-2, length).trim();
int count = Integer.parseInt(count_string);
System.out.println("Number of Image available to Swipe: "+count);
for (int i=0; i<=count; i++){
JavascriptExecutor js = (JavascriptExecutor) driver;
HashMap<String, String> scrollObject = new HashMap<String, String>();
scrollObject.put("direction", "right");
js.executeScript("mobile: scroll", scrollObject);
}
System.out.println("Swipe Successfully");
}
catch (Exception e)
{
System.out.println("Image swipe was not successfull");
}
return false;
}
Thanks!!!
Use the below method to Swipe and Scroll
public void scrollUpTo() {
Dimension size;
size = getCurrentDriver().manage().window().getSize();
double screenHeightStart = size.getHeight() * 0.5;
int scrollStart = (int) screenHeightStart;
double screenHeightEnd = size.getHeight() * 0.2;
int scrollEnd = (int) screenHeightEnd;
swipe(50, scrollStart, 0, scrollEnd, 2000);
}
Use the below method to swipe Right
public void initWidthSize() {
Dimension size = getCurrentDriver().manage().window().getSize();
startx = (int) (size.width * 0.90);
endx = (int) (size.width * 0.10);
starty = size.height / 2;
}
public void swiperToRightWithCoordinates(int starty) {
initWidthSize();
swipe(endx, starty, startx, starty, 1000);
}
use the below method to swipe Left
public void swiperToLeftWithCoordinates(int starty) {
initWidthSize();
swipe(startx, starty, endx, starty, 1000);
}
public void swiperToLeftWithBothCoordinates(int startx, int starty) {
initWidthSize();
swipe(startx, starty, endx, starty, 1000);
}
public void swiperToLeftWithTextContainsAndCoordinates(String name, int count, int coordinate) {
int i = 0;
do {
boolean isPresent = getCurrentDriver()
.findElement(By
.xpath("//XCUIElementTypeStaticText[#value='" + name + "']"))
.isDisplayed();
if (isPresent) {
break;
} else {
swiperToLeftWithCoordinates(coordinate);
}
i++;
} while (i <= count);
}
Use this latest code this is working for Appium Java Client 7.2.0
//Method - 1
public void voidSwipevertical(AndroidDriver<MobileElement> driver, double startPercentage, double endPercentage){
Dimension size=driver.manage().window().getSize();
int width=(int)(size.getWidth()/2);
int startPoint=(int)(size.getHeight()*startPercentage);
int endPoint=(int)(size.getHeight()*endPercentage);
new TouchAction(driver).press(PointOption.point(width, startPoint)).waitAction().moveTo(PointOption.point(width, endPoint)).release().perform();
}
//Method - 2
public void voidSwipevertical2(AndroidDriver<WebElement> driver, double startPercentage, double endPercentage){
Dimension size=driver.manage().window().getSize();
int width=(int)(size.getWidth()/2);
int startPoint=(int)(size.getHeight()*startPercentage);
int endPoint=(int)(size.getHeight()*endPercentage);
new TouchAction(driver).press(PointOption.point(width, startPoint)).moveTo(PointOption.point(width, endPoint)).release().perform();
}
//Method - 3
public void voidSwipevertical3(AndroidDriver<WebElement> driver, double startPercentage, double endPercentage) throws Exception{
Dimension size=driver.manage().window().getSize();
int width=(int)(size.getWidth()/2);
int startPoint=(int)(size.getHeight()*startPercentage);
int endPoint=(int)(size.getHeight()*endPercentage);
TouchAction action = new TouchAction(driver);
action.longPress(PointOption.point(width, startPoint)).moveTo(PointOption.point(width, endPoint)).release().perform();
}

Control Positioning of AdMob Banner in iOS via libGDX/RoboVM

I created my libGDX iOS project and I'm trying to position my AdMob ads to the bottom center of the screen but have no idea how to accomplish this. I'm using the bindings via RoboVM and do not know any of the RoboVM methods to control my ads. I copied the tutorial from here Does anyone have any tips or tutorials to help me accomplish this? Right now the ad seems to me missing 1/4 of whole banner ad is more towards the right of the screen. Below is my code:
public class IOSLauncher extends IOSApplication.Delegate implements IActivityRequestHandler{
private static final Logger log = new Logger(IOSLauncher.class.getName(), Application.LOG_DEBUG);
private static final boolean USE_TEST_DEVICES = true;
private GADBannerView adview;
private boolean adsInitialized = false;
private IOSApplication iosApplication;
#Override
protected IOSApplication createApplication() {
IOSApplicationConfiguration config = new IOSApplicationConfiguration();
config.orientationLandscape = true;
config.orientationPortrait = false;
iosApplication = new IOSApplication(new TestProject(this), config);
return iosApplication;
}
public static void main(String[] argv) {
NSAutoreleasePool pool = new NSAutoreleasePool();
UIApplication.main(argv, null, IOSLauncher.class);
pool.close();
}
#Override
public void hide() {
initializeAds();
final CGSize screenSize = UIScreen.getMainScreen().getBounds().size();
double screenWidth = screenSize.width();
final CGSize adSize = adview.getBounds().size();
double adWidth = adSize.width();
double adHeight = adSize.height();
log.debug(String.format("Hidding ad. size[%s, %s]", adWidth, adHeight));
float bannerWidth = (float) screenWidth;
float bannerHeight = (float) (bannerWidth / adWidth * adHeight);
adview.setFrame(new CGRect(0, -bannerHeight, bannerWidth, bannerHeight));
}
#Override
public void show() {
initializeAds();
final CGSize screenSize = UIScreen.getMainScreen().getBounds().size();
double screenWidth = screenSize.width();
final CGSize adSize = adview.getBounds().size();
double adWidth = adSize.width();
double adHeight = adSize.height();
log.debug(String.format("Showing ad. size[%s, %s]", adWidth, adHeight));
float bannerWidth = (float) screenWidth;
float bannerHeight = (float) (bannerWidth / adWidth * adHeight);
adview.setFrame(new CGRect((screenWidth / 2) - adWidth / 2, 0, bannerWidth, bannerHeight));
}
public void initializeAds() {
if (!adsInitialized) {
log.debug("Initalizing ads...");
adsInitialized = true;
adview = new GADBannerView(GADAdSize.banner());
adview.setAdUnitID(Constants.AdUnitID); //put your secret key here
adview.setRootViewController(iosApplication.getUIViewController());
iosApplication.getUIViewController().getView().addSubview(adview);
final GADRequest request = GADRequest.create();
adview.setDelegate(new GADBannerViewDelegateAdapter() {
#Override
public void didReceiveAd(GADBannerView view) {
super.didReceiveAd(view);
log.debug("didReceiveAd");
}
#Override
public void didFailToReceiveAd(GADBannerView view,
GADRequestError error) {
super.didFailToReceiveAd(view, error);
log.debug("didFailToReceiveAd:" + error);
}
});
adview.loadRequest(request);
log.debug("Initalizing ads complete.");
}
}
#Override
public void showAds(boolean show) {
initializeAds();
final CGSize screenSize = UIScreen.getMainScreen().getBounds().size();
double screenWidth = screenSize.width();
final CGSize adSize = adview.getBounds().size();
double adWidth = adSize.width();
double adHeight = adSize.height();
log.debug(String.format("Hidding ad. size[%s, %s]", adWidth, adHeight));
float bannerWidth = (float) screenWidth;
float bannerHeight = (float) (bannerWidth / adWidth * adHeight);
if(show) {
adview.setFrame(new CGRect((screenWidth / 2) - adWidth / 2, 0, bannerWidth, bannerHeight));
} else {
adview.setFrame(new CGRect(0, -bannerHeight, bannerWidth, bannerHeight));
}
you set the ad position with
adview.setFrame(CGRect);
if you inspect the parameters of CGRect it's like;
CGRect(double x, double y, double width, double height)
0,0 coordinates (x,y) is top left. so, your code;
// center of screen
double adX = (screenWidth / 2) - (adWidth / 2);
// bottom of screen
double adY = screenHeight - bannerHeight;
adview.setFrame(new CGRect(adX, adY, bannerWidth, bannerHeight));
and the other important thing, you should not manipulate the positioning in two method! your showAds method should be like;
public void showAds(boolean show) {
if (show) {
show();
} else {
hide();
}
}

JavaFX WebView loading page in background

I have a problem using the JavaFX WebView. What I want to achieve is pre-fetching a web page in the background and visualiszing it only when the page is totally loaded.
I have made a simple exmaple program to reproduce the problem. After the page is loaded I enable a button. A Click on this button then makes the WebView visible.
The problem I have is, that if I click on the button when it gets enabled, the web page is not visible directly. Instead the following happens: At first there is a totally white panel and then after a short time the web page is visible. I don't understand why the page is not visible directly. How can I achieve it, that the web page is directly visible?
The following link points to an animated gif which shows the behaviour:
http://tinypic.com/view.php?pic=oh66bl&s=5#.Ujmv1RddWKk
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.embed.swing.JFXPanel;
import javafx.scene.Scene;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class WebViewTest extends javax.swing.JPanel {
private static JFXPanel browserFxPanel;
private WebView webView;
private WebEngine eng;
/**
* Creates new form WebViewTest
*/
public WebViewTest() {
initComponents();
Platform.setImplicitExit(false);
browserFxPanel = new JFXPanel();
Platform.runLater(new Runnable() {
public void run() {
webView = createBrowser();
Scene scene = new Scene(webView);
scene.setFill(null);
browserFxPanel.setScene(
scene);
}
});
}
/**
* This method is called from within the constructor to initialize the form. WARNING: Do NOT modify this code. The
* content of this method is always regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
pnlMain = new javax.swing.JPanel();
showWebpageButton = new javax.swing.JButton();
setLayout(new java.awt.GridBagLayout());
pnlMain.setLayout(new java.awt.BorderLayout());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridwidth = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
add(pnlMain, gridBagConstraints);
showWebpageButton.setText("show web page");
showWebpageButton.setEnabled(false);
showWebpageButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
showWebpageButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10);
add(showWebpageButton, gridBagConstraints);
}// </editor-fold>
private void showWebpageButtonActionPerformed(java.awt.event.ActionEvent evt) {
pnlMain.removeAll();
pnlMain.add(browserFxPanel, BorderLayout.CENTER);
WebViewTest.this.invalidate();
WebViewTest.this.revalidate();
}
// Variables declaration - do not modify
private javax.swing.JPanel pnlMain;
private javax.swing.JButton showWebpageButton;
// End of variables declaration
private WebView createBrowser() {
Double widthDouble = pnlMain.getSize().getWidth();
Double heightDouble = pnlMain.getSize().getHeight();
final WebView view = new WebView();
view.setMinSize(widthDouble, heightDouble);
view.setPrefSize(widthDouble, heightDouble);
eng = view.getEngine();
eng.load("http://todomvc.com/architecture-examples/angularjs/#/");
eng.getLoadWorker().workDoneProperty().addListener(new ChangeListener<Number>() {
public void changed(ObservableValue<? extends Number> ov, Number t, Number t1) {
final double workDone = eng.getLoadWorker().getWorkDone();
final double totalWork = eng.getLoadWorker().getTotalWork();
if (workDone == totalWork) {
showWebpageButton.setEnabled(true);
}
}
});
return view;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
final JFrame f = new JFrame("Navigator Dummy");
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setSize(new Dimension(1024, 800));
final WebViewTest navDummy = new WebViewTest();
f.getContentPane().add(navDummy);
f.setVisible(true);
}
});
}
}
JFX needs a "stage" to show up its face. Modify your codes as following and it will work perfectly
/**
* Creates new form WebViewTest
*/
private Stage stage; // insert this line
public WebViewTest() {
initComponents();
Platform.setImplicitExit(false);
browserFxPanel = new JFXPanel();
Platform.runLater(new Runnable() {
public void run() {
webView = createBrowser();
Scene scene = new Scene(webView);
scene.setFill(null);
stage = new Stage(); // <<<
stage.setScene(scene); // <<<
browserFxPanel.setScene(scene);
}
});
}
...
private void showWebpageButtonActionPerformed(java.awt.event.ActionEvent evt) {
pnlMain.removeAll();
pnlMain.add(browserFxPanel, BorderLayout.CENTER);
WebViewTest.this.invalidate();
WebViewTest.this.revalidate();
stage.show(); // <<< afer click Button
}

customize Edit field on blackberry

I want to customize Edit Field like in this link http://www.hostingpics.net/viewer.php?id=44669634im.png.
I find this code
------------------------------------------------CustomTextBox---------------------
package mypackage;
import net.rim.device.api.ui.Manager;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.component.EditField;
import net.rim.device.api.ui.component.BasicEditField;
import net.rim.device.api.system.EncodedImage;
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.Display;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.system.Characters;
import net.rim.device.api.math.Fixed32;
import net.rim.device.api.ui.DrawStyle;
import net.rim.device.api.ui.Font;
public class CustomTextBox extends Manager
{
/**
* Default margins
*/
private final static int DEFAULT_LEFT_MARGIN = 10;
private final static int DEFAULT_RIGHT_MARGIN = 10;
private final static int DEFAULT_TOP_MARGIN = 5;
private final static int DEFAULT_BOTTOM_MARGIN = 5;
/**
* Default paddings
*/
private final static int DEFAULT_LEFT_PADDING = 10;
private final static int DEFAULT_RIGHT_PADDING = 10;
private final static int DEFAULT_TOP_PADDING = 5;
private final static int DEFAULT_BOTTOM_PADDING = 5;
/**
* Margins around the text box
*/
private int topMargin = DEFAULT_TOP_MARGIN;
private int bottomMargin = DEFAULT_BOTTOM_MARGIN;
private int leftMargin = DEFAULT_LEFT_MARGIN;
private int rightMargin = DEFAULT_RIGHT_MARGIN;
/**
* Padding around the text box
*/
private int topPadding = DEFAULT_TOP_PADDING;
private int bottomPadding = DEFAULT_BOTTOM_PADDING;
private int leftPadding = DEFAULT_LEFT_PADDING;
private int rightPadding = DEFAULT_RIGHT_PADDING;
/**
* Amount of empty space horizontally around the text box
*/
private int totalHorizontalEmptySpace = leftMargin + leftPadding
+ rightPadding + rightMargin;
/**
* Amount of empty space vertically around the text box
*/
private int totalVerticalEmptySpace = topMargin + topPadding
+ bottomPadding + bottomMargin;
/**
* Minimum height of the text box required to display the text entered
*/
private int minHeight = getFont().getHeight() + totalVerticalEmptySpace;
/**
* Width of the text box
*/
private int width = Display.getWidth();
/**
* Height of the text box
*/
private int height = minHeight;
/**
* Background image for the text box
*/
private EncodedImage backgroundImage;
/**
* Bitmap version of the backgroundImage.
* Needed to reduce the calculation overhead incurred by
* scaling of the given image
* and derivation of Bitmap from the
* EncodedImage every time it is needed.
*/
private Bitmap bitmapBackgroundImage;
/**
* The core element of this text box
*/
private EditField editField;
//private BasicEditField editField;
//private String entireText;
public CustomTextBox()
{
// Let the super class initialize the core
super(0);
// An edit field is the sole field of this manager.
editField = new EditField();
//editField = new CustomEditField();
add(editField);
}
public CustomTextBox(EncodedImage backgroundImage)
{
this();
setBackgroundImage(backgroundImage);
}
public void setSize(int width, int height)
{
boolean isChanged = false;
if (width > 0 // Ignore invalid width
&& this.width != width)
{
this.width = width;
isChanged = true;
}
// Ignore the specified height if it is less
// than the minimum height required to display the text.
if (height > minHeight && height != this.height)
{
this.height = height;
isChanged = true;
}
// If width/height has been changed and background image
// is available, adapt it to the new dimension
if (isChanged == true && backgroundImage != null)
{
bitmapBackgroundImage = getScaledBitmapImage(backgroundImage,
this.width - (leftMargin+rightMargin),
this.height - (topMargin+bottomMargin));
}
}
public void setWidth(int width)
{
if (width > 0 && width != this.width)
{
this.width = width;
// If background image is available, adapt it to the new width
if (backgroundImage != null)
{
bitmapBackgroundImage = getScaledBitmapImage(backgroundImage,
this.width - (leftMargin+rightMargin),
this.height - (topMargin+bottomMargin));
}
}
}
public void setHeight(int height)
{
// Ignore the specified height if it is
// less than the minimum height required to display the text.
if (height > minHeight)
{
this.height = height;
// If background image is available, adapt it to the new width
if (backgroundImage != null)
{
bitmapBackgroundImage = getScaledBitmapImage(backgroundImage,
this.width - (leftMargin+rightMargin),
this.height - (topMargin+bottomMargin));
}
}
}
public void setBackgroundImage(EncodedImage backgroundImage)
{
this.backgroundImage = backgroundImage;
// Consider the height of background image in
// calculating the height of the text box.
// setHeight() does not ensure that specified
// height will be in effect, of course, for valid reasons.
// So derivation of Bitmap image in the setHeight() method is not sure.
setHeight(backgroundImage.getHeight() + topMargin + bottomMargin);
if (bitmapBackgroundImage == null)
{
bitmapBackgroundImage = getScaledBitmapImage(backgroundImage,
this.width - (leftMargin+rightMargin),
this.height - (topMargin+bottomMargin));
}
}
/**
* Generate and return a Bitmap Image scaled according
* to the specified width and height.
*
* #param image EncodedImage object
* #param width Intended width of the returned Bitmap object
* #param height Intended height of the returned Bitmap object
* #return Bitmap object
*/
private Bitmap getScaledBitmapImage(EncodedImage image, int width, int height)
{
// Handle null image
if (image == null)
{
return null;
}
int currentWidthFixed32 = Fixed32.toFP(image.getWidth());
int currentHeightFixed32 = Fixed32.toFP(image.getHeight());
int requiredWidthFixed32 = Fixed32.toFP(width);
int requiredHeightFixed32 = Fixed32.toFP(height);
int scaleXFixed32 = Fixed32.div(currentWidthFixed32, requiredWidthFixed32);
int scaleYFixed32 = Fixed32.div(currentHeightFixed32, requiredHeightFixed32);
image = image.scaleImage32(scaleXFixed32, scaleYFixed32);
return image.getBitmap();
}
protected void sublayout(int width, int height)
{
// We have one and only child - the edit field.
// Place it at the appropriate place.
Field field = getField(0);
layoutChild(field, this.width - totalHorizontalEmptySpace,
this.height - totalVerticalEmptySpace);
setPositionChild(field, leftMargin+leftPadding, topMargin+topPadding);
setExtent(this.width, this.height);
}
public void setTopMargin(int topMargin)
{
this.topMargin = topMargin;
}
public void setBottomMargin(int bottomMargin)
{
this.bottomMargin = bottomMargin;
}
protected void paint(Graphics graphics)
{
// Draw background image if available, otherwise draw a rectangle
if (bitmapBackgroundImage == null)
{
graphics.drawRect(leftMargin, topMargin,
width - (leftMargin+rightMargin), height - (topMargin+bottomMargin));
graphics.drawRoundRect(leftMargin, topMargin,
width - (leftMargin+rightMargin),
height - (topMargin+bottomMargin), 5, 5);
}
else
{
graphics.drawBitmap(leftMargin, topMargin,
width - (leftMargin+rightMargin),
height - (topMargin+bottomMargin),
bitmapBackgroundImage, 0, 0);
}
// Determine the rightward text that can fit into the visible edit field
EditField ef = (EditField)getField(0);
String entireText = ef.getText();
boolean longText = false;
String textToDraw = "";
Font font = getFont();
int availableWidth = width - totalHorizontalEmptySpace;
if (font.getAdvance(entireText) <= availableWidth)
{
textToDraw = entireText;
}
else
{
int endIndex = entireText.length();
for (int beginIndex = 1; beginIndex < endIndex; beginIndex++)
{
textToDraw = entireText.substring(beginIndex);
if (font.getAdvance(textToDraw) <= availableWidth)
{
longText = true;
break;
}
}
}
if (longText == true)
{
// Force the edit field display only the truncated text
ef.setText(textToDraw);
// Now let the components draw themselves
super.paint(graphics);
// Return the text field its original text
ef.setText(entireText);
}
else
{
super.paint(graphics);
}
}
public int getPreferredWidth()
{
return width;
}
public int getPreferredHeight()
{
return height;
}
protected boolean keyChar(char ch, int status, int time)
{
if (ch == Characters.ENTER)
{
return true;
}
else
{
return super.keyChar(ch, status, time);
}
}
public String getText()
{
return ((EditField)getField(0)).getText();
}
public void setText(final String text)
{
((EditField)getField(0)).setText(text);
}
}
--------------------------------------------MyScreen------------------------
package mypackage;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.container.MainScreen;
/**
* A class extending the MainScreen class, which provides default standard
* behavior for BlackBerry GUI applications.
*/
public final class MyScreen extends MainScreen
{
public MyScreen()
{
new CustomTextBox();
}
}
--------------------------------------------MyApp------------------------
package mypackage;
import net.rim.device.api.ui.UiApplication;
/**
* This class extends the UiApplication class, providing a
* graphical user interface.
*/
public class MyApp extends UiApplication
{
public static void main(String[] args)
{
// Create a new instance of the application and make the currently
// running thread the application's event dispatch thread.
MyApp theApp = new MyApp();
theApp.enterEventDispatcher();
}
public MyApp()
{
// Push a screen onto the UI stack for rendering.
pushScreen(new MyScreen());
}
}
But I obtain white Screen what should I change in this code to ibtain the custon edit field
hi you just create object but you forget to add that object to mainscreen
package mypackage;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.container.MainScreen;
/**
* A class extending the MainScreen class, which provides default standard
* behavior for BlackBerry GUI applications.
*/
public final class MyScreen extends MainScreen
{
public MyScreen()
{
add(new CustomTextBox());//in your code it is like new CustomTextBox();
}
}
if you want to add any image as background to your editbox then you can yous following way
package mypackage;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.container.MainScreen;
/**
* A class extending the MainScreen class, which provides default standard
* behavior for BlackBerry GUI applications.
*/
public final class MyScreen extends MainScreen
{
public MyScreen()
{
EncodedImage enc_img=EncodedImage.getEncodedImageResource("input-box.png");//image name is 'input-box.png'
CustomTextBox edi_box=new CustomTextBox(enc_img);
add(edi_box);
}
}

Mysterious extra pixels in ButtonField?

I have created a very basic custom layout to set out a menu made up of ButtonFields.
To position them vertically, i split the screen into 6 and then put them at divides 2,3,4 and 5 as is shown in the code.
So for the emulator, the Torch, a Height of 480 would see buttons at 160,240,320 and 400.
However, when I check them, they are all 24 pixels below this, and there seems no obvious reason unless this is just a typical convention I have missed!
package Test;
import net.rim.device.api.system.Display;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.container.VerticalFieldManager;
class MenuLayoutManager extends VerticalFieldManager{
public MenuLayoutManager()
{
super();
}
public int getPreferredWidth()
{
int preferredWidth = Display.getWidth();
return preferredWidth;
}
protected void sublayout(int inMaxWidth, int inMaxHeight)
{
int xCentre = Display.getWidth()/2;
int yGap = Display.getHeight() / 6;
int xPos = 0;
int yPos = yGap * 2;
int fieldNo = this.getFieldCount();
for(int index = 0; index<fieldNo; index++)
{
Field aField = this.getField(index);
this.layoutChild(aField, inMaxWidth, inMaxHeight);
xPos = xCentre - (aField.getWidth() / 2);
this.setPositionChild(aField, xPos, yPos);
yPos += yGap;
}
this.setExtent(inMaxWidth, inMaxHeight);
}
}
------Entry point and button creation----
package Test;
import net.rim.device.api.ui.component.ButtonField;
import net.rim.device.api.ui.container.MainScreen;
class MyScreen extends MainScreen
{
public MyScreen(){
super(MainScreen.NO_VERTICAL_SCROLL|MainScreen.NO_VERTICAL_SCROLLBAR);
this.initialize();
}
private void initialize()
{
// Set the displayed title of the screen
this.setTitle(String.valueOf("Ben's Menu"));
MenuLayoutManager mlm = new MenuLayoutManager();
ButtonField Button1 = new ButtonField("New Game");
ButtonField Button2 = new ButtonField("High Scores");
ButtonField Button3 = new ButtonField("Instructions");
ButtonField Button4 = new ButtonField("Exit");
mlm.add(Button1);
mlm.add(Button2);
mlm.add(Button3);
mlm.add(Button4);
this.add(mlm);
}
}
With a MainScreen, you don't get the full display height allocated to the screen contents. (At a minimum, IIRC, there's the title and a separator.) Try using a FullScreen instead and see what happens.

Resources