Control Positioning of AdMob Banner in iOS via libGDX/RoboVM - ios

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();
}
}

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();
}

Implementing AdMob into my iOS libgdx game?

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.

Vertical Scroll TextField in Blackberry

I am new to Blackberry developement.I want do the custom textfield in my application.
I write a code for that But I want to scroll the text in that text field (if me text in textfield extends above 4 line.)
I use manager class to add vertical scroll but cant get it.
TextField textfield1=new TextField(Manager.VERTICAL_SCROLL);
Anybody know how to give vertical scroll to the text field.
Try the following code:
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.Manager;
import net.rim.device.api.ui.component.TextField;
import net.rim.device.api.ui.container.VerticalFieldManager;
public class MyTextField extends VerticalFieldManager {
private int fieldWidth;
private int fieldHeight;
private TextField textField;
public MyTextField(int width, int height) {
super(Manager.NO_VERTICAL_SCROLL);
fieldWidth = width;
fieldHeight = height;
VerticalFieldManager vfm = new VerticalFieldManager(Manager.VERTICAL_SCROLL|Manager.VERTICAL_SCROLLBAR);
textField = new TextField() {
public void paint(Graphics g) {
getManager().invalidate();
super.paint(g);
}
};
vfm.add(textField);
add(vfm);
}
public void paint(Graphics g) {
// draw the border of the text area;
int color = g.getColor();
g.setColor(0x00FFCC);
g.drawRect(0, 0, fieldWidth, fieldHeight);
g.setColor(color);
super.paint(g);
}
public void sublayout(int width, int height) {
if (fieldWidth == 0) {
fieldWidth = width;
}
if (fieldHeight == 0) {
fieldHeight = height;
}
super.sublayout(fieldWidth, fieldHeight);
setExtent(fieldWidth,fieldHeight);
}
public String getText() {
return textField.getText();
}
public void setText(String text) {
textField.setText(text);
}
}
add it to your Screen or Manager by specifying the size like this:
add(new MyTextField(200, 200));
Create
HorizontalFieldManager HorizontalFieldManager=new HorizontalFieldManager(Manager.VERTICAL_SCROLL);
Then
TextField textfield1=new TextField();
HorizontalFieldManager.add(textfield1);
add(HorizontalFieldManager);
you can use custom textbox as bellow.
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);
}
}

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);
}
}

Custom multi line textbox in Blackberry

Can any one tell me how to create multi line text box with increasing height with background color.
Thank You
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);
}
}
you can use EditField in APIs and assign a background to it by:
yourEditField.setBackground(yourBackground);

Resources