While working on a blackberry project I was required to display a round corner text field with a place holder text. The logic was to display place holder text when TextField is not in focus and no text is entered by user (or text is cleared by user). As soon as TextField receives focus, placeholder text should be removed. Displaying place holder text when TextField is empty is very easy . You can just override TextField's paint method and check if text is empty you can set text to place holder text. Here is a simple example
But displaying and removing of placeholder text on focus and unfocus was a bit of task so I came up with my own class and want to share with other fellow coders.
Do let me know how I can improve this class to make it more easy to use and understand.
protected void paint(Graphics g){
if (getText().compareTo("")==0){
setText("Place holder text..");
}
super.paint(g);
}
But displaying and removing of placeholder text on focus and unfocus was a bit of task so I came up with my own class and want to share with other fellow coders.
import net.rim.device.api.ui.Color;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.component.TextField;
public class RoundTextField
extends TextField {
private int fieldWidth,fieldHeight;
private String defaultText;
public boolean autoText=true;
public RoundTextField(int width,int height,long style){
super(style);
fieldWidth=width;
fieldHeight=height;
setPadding(2,0,0,4);
defaultText="";
}
public RoundTextField(int width,int height,String defaultText,long style){
this(width,height,style);
this.defaultText=defaultText;
setText(this.defaultText);
autoText=true;
}
protected boolean keyUp(int code,int t){
autoText=false;
return super.keyUp(code,t);
}
public void setText(String str){
super.setText(str);
autoText=false;
}
private String getFinalText(){
if (autoText){
return defaultText;
}
return super.getText();
}
public String getText(){
if (autoText){
return "";
}
return super.getText();
}
protected void paintBackground(Graphics g){
g.setColor(Color.WHITE);
g.fillRoundRect(0,0,getWidth()-2,getHeight()-2,10,10);
g.setColor(Color.GRAY);
g.drawRoundRect(0,0,getWidth(),getHeight(),10,10);
}
protected void paint(Graphics g){
g.setColor(Color.GRAY);
super.paint(g);
}
protected void layout(int width,int height){
super.layout(fieldWidth,fieldHeight);
setExtent(fieldWidth,fieldHeight);
}
protected void onFocus(int dir){
if (autoText){
if (getFinalText().compareTo(defaultText)==0)
setText("");
}
autoText=false;
}
protected void onUnfocus(){
if (!autoText){
if (getFinalText().compareTo("")==0){
setText(defaultText);
autoText=true;
}
}
}
}
Do let me know how I can improve this class to make it more easy to use and understand.
nice one rameez!
ReplyDeletethanks Azfar.
ReplyDelete