ClassCastException of LayoutParams to MarginLayoutParams after setting a view's width - android-layout

I've written a small proxy class so that I can use ObjectAnimator to animate a view's margin. After checking that this worked and everything animated properly, I wanted to adjust the view's size before the animation, but after I set the width, my animation fails with the ClassCastException. I haven't a clue why.
private class handleClickListener implements View.OnClickListener {
private static final int LEFT_MARGIN_VISIBLE = 0;
private static final int LEFT_MARGIN_HIDDEN = -196;
public void onClick(View view) {
LinearLayout row = (LinearLayout) view.getParent().getParent();
RelativeLayout options = (RelativeLayout) row.findViewById(R.id.options);
LayoutProxy layoutProxy = new LayoutProxy(options);
// First make sure the options are the right width to fill the screen with the handle
int rowWidth = row.getWidth();
int handleWidth = view.getWidth();
layoutProxy.setWidth(rowWidth - handleWidth);
ObjectAnimator animation;
if (layoutProxy.getLeftMargin() == Util.dipsToPixels(options, LEFT_MARGIN_VISIBLE)) {
animation = ObjectAnimator.ofInt(layoutProxy, "leftMargin", Util.dipsToPixels(view, LEFT_MARGIN_VISIBLE), Util.dipsToPixels(view, LEFT_MARGIN_HIDDEN));
} else {
animation = ObjectAnimator.ofInt(layoutProxy, "leftMargin", Util.dipsToPixels(view, LEFT_MARGIN_HIDDEN), Util.dipsToPixels(view, LEFT_MARGIN_VISIBLE));
}
animation.setDuration(200);
animation.start();
}
/**
* Allows an ObjectAnimator to set/get margins and dimensions of a view
*/
private class LayoutProxy {
private ViewGroup mView;
public LayoutProxy(View view) {
mView = (ViewGroup) view;
}
public int getWidth() {
ViewGroup.LayoutParams lp = mView.getLayoutParams();
return lp.width;
}
public void setWidth(int width) {
ViewGroup.LayoutParams lp = mView.getLayoutParams();
mView.setLayoutParams(new ViewGroup.LayoutParams(width, lp.height));
}
public int getHeight() {
ViewGroup.LayoutParams lp = mView.getLayoutParams();
return lp.height;
}
public void setHeight(int height) {
ViewGroup.LayoutParams lp = mView.getLayoutParams();
mView.setLayoutParams(new ViewGroup.LayoutParams(lp.width, height));
}
public int getLeftMargin() {
ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) mView.getLayoutParams();
return lp.leftMargin;
}
public void setLeftMargin(int margin) {
MarginLayoutParams lp = (MarginLayoutParams) mView.getLayoutParams();
lp.setMargins(margin, lp.topMargin, lp.rightMargin, lp.bottomMargin);
mView.requestLayout();
}
public int getTopMargin() {
MarginLayoutParams lp = (MarginLayoutParams) mView.getLayoutParams();
return lp.topMargin;
}
public void setTopMargin(int margin) {
MarginLayoutParams lp = (MarginLayoutParams) mView.getLayoutParams();
lp.setMargins(lp.leftMargin, margin, lp.rightMargin, lp.bottomMargin);
mView.requestLayout();
}
public int getRightMargin() {
MarginLayoutParams lp = (MarginLayoutParams) mView.getLayoutParams();
return lp.rightMargin;
}
public void setRightMargin(int margin) {
MarginLayoutParams lp = (MarginLayoutParams) mView.getLayoutParams();
lp.setMargins(lp.leftMargin, lp.topMargin, margin, lp.bottomMargin);
mView.requestLayout();
}
public int getBottomMargin() {
MarginLayoutParams lp = (MarginLayoutParams) mView.getLayoutParams();
return lp.bottomMargin;
}
public void setBottomMargin(int margin) {
MarginLayoutParams lp = (MarginLayoutParams) mView.getLayoutParams();
lp.setMargins(lp.leftMargin, lp.topMargin, lp.rightMargin, margin);
mView.requestLayout();
}
}
}
And the error:
FATAL EXCEPTION: main
java.lang.ClassCastException: android.view.ViewGroup$LayoutParams cannot be cast to android.view.ViewGroup$MarginLayoutParams
at com.test.data.ContactListCursorAdapter$handleClickListener$LayoutProxy.getLeftMargin(ContactListCursorAdapter.java:135)
at com.test.data.ContactListCursorAdapter$handleClickListener.onClick(ContactListCursorAdapter.java:94)
at android.view.View.performClick(View.java:4084)
at android.view.View$PerformClick.run(View.java:16966)

I have similar problem
At first I was using:
LayoutParams viewFlowLayout = new LayoutParams(originalWidth, newHeight);
viewFlow.setLayoutParams(flowViewLayout);
And I have the same error message as yours:
java.lang.ClassCastException: android.view.ViewGroup$LayoutParams cannot be cast to android.view.ViewGroup$MarginLayoutParams
which I have no idea why as i didn't use MarginLayoutParams.
Then I try and change it to this
LayoutParams viewFlowLayout = viewFlow.getLayoutParams();
viewFlowLayout.height = newheight;
viewFlow.setLayoutParams(flowViewLayout);
And the error disappear...
I guess you have multiple use case for the above code.
For example: Change this
public void setHeight(int height) {
ViewGroup.LayoutParams lp = mView.getLayoutParams();
mView.setLayoutParams(new ViewGroup.LayoutParams(lp.width, height));
}
to
public void setHeight(int height) {
ViewGroup.LayoutParams lp = mView.getLayoutParams();
lp.height = height //width will remain and height will be change to the newHeight
mView.setLayoutParams(lp);
}
Hope that it will be helpful to you and many people out there...

I just want to know the reason why you are casting LayoutParams to MarginLayoutParams. Is there a specific reason? Because i think the problem lies there.

Related

Imagebutton overlays after zooming- how to fix?

I have a problem. Right now I have two imagebuttons. When I click on the first button to increase the image the button next to it is still availble in the screen. I dont know to set the selected screen in the foreground?
Can anybody help?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bewerbung);
final View thumb1View = findViewById(R.id.thumb_button_1);
thumb1View.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
zoomImageFromThumb(thumb1View, R.drawable.anschreiben1);
}
});
final View thumb2View = findViewById(R.id.thumb_button_2);
thumb2View.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
zoomImageFromThumb(thumb2View, R.drawable.anschreiben2);
}
});
mShortAnimationDuration = getResources().getInteger(
android.R.integer.config_shortAnimTime);
}
private void zoomImageFromThumb(final View thumbView, int imageResId) {
if (mCurrentAnimator != null) {
mCurrentAnimator.cancel();
}
final ImageView expandedImageView = (ImageView) findViewById(
R.id.expanded_image);
expandedImageView.setImageResource(imageResId);
final Rect startBounds = new Rect();
final Rect finalBounds = new Rect();
final Point globalOffset = new Point();
thumbView.getGlobalVisibleRect(startBounds);
findViewById(R.id.container)
.getGlobalVisibleRect(finalBounds, globalOffset);
startBounds.offset(-globalOffset.x, -globalOffset.y);
finalBounds.offset(-globalOffset.x, -globalOffset.y);
float startScale;
if ((float) finalBounds.width() / finalBounds.height()
> (float) startBounds.width() / startBounds.height()) {
startScale = (float) startBounds.height() / finalBounds.height();
float startWidth = startScale * finalBounds.width();
float deltaWidth = (startWidth - startBounds.width()) / 2;
startBounds.left -= deltaWidth;
startBounds.right += deltaWidth;
} else {
startScale = (float) startBounds.width() / finalBounds.width();
float startHeight = startScale * finalBounds.height();
float deltaHeight = (startHeight - startBounds.height()) / 2;
startBounds.top -= deltaHeight;
startBounds.bottom += deltaHeight;
}
thumbView.setAlpha(0f);
expandedImageView.setVisibility(View.VISIBLE);
expandedImageView.setPivotX(0f);
expandedImageView.setPivotY(0f);
AnimatorSet set = new AnimatorSet();
set
.play(ObjectAnimator.ofFloat(expandedImageView, View.X,
startBounds.left, finalBounds.left))
.with(ObjectAnimator.ofFloat(expandedImageView, View.Y,
startBounds.top, finalBounds.top))
.with(ObjectAnimator.ofFloat(expandedImageView, View.SCALE_X,
startScale, 1f)).with(ObjectAnimator.ofFloat(expandedImageView,
View.SCALE_Y, startScale, 1f));
set.setDuration(mShortAnimationDuration);
set.setInterpolator(new DecelerateInterpolator());
set.addListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
mCurrentAnimator = null;
}
#Override
public void onAnimationCancel(Animator animation) {
mCurrentAnimator = null;
}
});
set.start();
mCurrentAnimator = set;
final float startScaleFinal = startScale;
expandedImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mCurrentAnimator != null) {
mCurrentAnimator.cancel();
}
AnimatorSet set = new AnimatorSet();
set.play(ObjectAnimator
.ofFloat(expandedImageView, View.X, startBounds.left))
.with(ObjectAnimator
.ofFloat(expandedImageView,
View.Y, startBounds.top))
.with(ObjectAnimator
.ofFloat(expandedImageView,
View.SCALE_X, startScaleFinal))
.with(ObjectAnimator
.ofFloat(expandedImageView,
View.SCALE_Y, startScaleFinal));
set.setDuration(mShortAnimationDuration);
set.setInterpolator(new DecelerateInterpolator());
set.addListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
thumbView.setAlpha(1f);
expandedImageView.setVisibility(View.GONE);
mCurrentAnimator = null;
}
#Override
public void onAnimationCancel(Animator animation) {
thumbView.setAlpha(1f);
expandedImageView.setVisibility(View.GONE);
mCurrentAnimator = null;
}
});
set.start();
mCurrentAnimator = set;
}
});
}
}

How to add more than one same custom view to a grid layout in android from Java code

I am learning custom views in android.
I made one custom view, with a rectangle and a text. The code of the custom view is:
public class TileGenerator extends View {
// rectangle parameters
private Rect rect = new Rect();
private Paint rectPaint = new Paint();
private Integer rectEndX;
private Integer rectEndY;
private Integer rectStartX;
private Integer rectStartY;
private Integer rectFillColor;
private Float rectTextStartX;
private Float rectTextStartY;
//rectangle text
private String rectText;
private Paint rectTextPaint = new Paint();
public TileGenerator(Context context) {
super(context);
}
#Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
public void setTileTitleText(String rectText) {
this.rectText = rectText;
}
#Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
rectEndX = getrectEndX();
rectEndY = getrectEndY();
rectStartX = getRectStartX();
rectStartY = getRectStartY();
rectTextStartX = rectEndX/4f + rectStartX;
rectTextStartY = 3.5f * rectEndY/4f + rectStartY;
rectTextPaint.setTextSize(rectEndY/8);
rectTextPaint.setColor(Color.BLACK);
rect.set(rectStartX,rectStartY,rectEndX,rectEndY);
rectPaint.setColor(getRectFillColor());
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawRect(rect, rectPaint);
canvas.drawText(rectText,rectTextStartX,rectTextStartY,rectTextPaint );
}
#Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
}
public Integer getrectEndX() {
return rectEndX;
}
public void setrectEndX(Integer rectEndX) {
this.rectEndX = rectEndX;
}
public Integer getrectEndY() {
return rectEndY;
}
public void setrectEndY(Integer rectEndY) {
this.rectEndY = rectEndY;
}
public Integer getRectStartX() {
return rectStartX;
}
public void setRectStartX(Integer rectStartX) {
this.rectStartX = rectStartX;
}
public Integer getRectStartY() {
return rectStartY;
}
public void setRectStartY(Integer rectStartY) {
this.rectStartY = rectStartY;
}
public Integer getRectFillColor() {
return rectFillColor;
}
public void setRectFillColor(Integer rectFillColor) {
this.rectFillColor = rectFillColor;
}
public String getRectText() {
return rectText;
}
}
After that I created an blank activity. I am doing all with JAVA code. No XML. Then I try to add above custom view to a gridview layout. I want to add two custom views with different text in a horizontal gridview. So far my code is as below:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GridLayout gridLayout = new GridLayout(this);
// first custom view
CustomRectWithText customRectWithText = new CustomRectWithText(this);
customRectWithText.setRectEndX(200);
customRectWithText.setRectEndY(200);
customRectWithText.setRectStartX(2);
customRectWithText.setRectStartY(2);
customRectWithText.setImage(image);
customRectWithText.setRectText("Text");
customRectWithText.setRectFillColor(Color.BLUE);
gridLayout.addView(customRectWithText);
// second custom view
CustomRectWithText customRectWithText1 = new CustomRectWithText(this);
customRectWithText1.setRectEndX(400);
customRectWithText1.setRectEndY(200);
customRectWithText1.setRectStartX(200 + 5);
customRectWithText1.setRectStartY(2);
customRectWithText1.setTileTitleText("Text 1");
customRectWithText1.setRectFillColor(Color.GREEN);
gridLayout.addView(customRectWithText1);
setContentView(gridLayout);
}
But still I am not getting both of the rectangles in a grid view. Only one rectangle is displayed at a time. In above case only first custom view is displayed.
Where am I doing wrong.
All I want is to make a repetitive rectangle of varying labels of any size inside a grid view.
Is this the way to do it. I mean is there any other way around.
I dont want to use ListItems.
Sorry but i do not have enough repo to comment.
But why dont you make an adapter?
Gridview behaves same as listView.
Use adapter to fill your grid.
This is the proper way to populate listView and gridView also.

JavaFX typewriter effect for label

i have some problem with this method. it works fine, but with one little problem. there is too little time among i call this method. so only the last String is printed on a label. but i want that the next String starting printed, only after previous String is finished.
Sorry for my English((
public void some(final String s) {
final Animation animation = new Transition() {
{
setCycleDuration(Duration.millis(2000));
}
protected void interpolate(double frac) {
final int length = s.length();
final int n = Math.round(length * (float) frac);
javafx.application.Platform.runLater(new Runnable() {
#Override
public void run() {
status.setValue(s.substring(0, n));
}
}
);
}
};
animation.play();
}
Use the following code to get a typewriting effect.
public void AnimateText(Label lbl, String descImp) {
String content = descImp;
final Animation animation = new Transition() {
{
setCycleDuration(Duration.millis(2000));
}
protected void interpolate(double frac) {
final int length = content.length();
final int n = Math.round(length * (float) frac);
lbl.setText(content.substring(0, n));
}
};
animation.play();
}
I don't know if it is an effect that you are trying to achieve, but I have created (ugly) demo how you can do this with TimeLine
public class Main extends Application {
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) throws Exception {
IntegerProperty letters= new SimpleIntegerProperty(0);
Label label = new Label();
Button animate = new Button("animate");
letters.addListener((a, b, c) -> {
label.setText("animate".substring(0, c.intValue()));
});
animate.setOnAction((e)->{
Timeline timeline = new Timeline();
KeyValue kv = new KeyValue(letters, "animate".length());
KeyFrame kf = new KeyFrame(Duration.seconds(3), kv);
timeline.getKeyFrames().add(kf);
timeline.play();
});
BorderPane pane = new BorderPane(label, null, null, animate, null);
primaryStage.setScene(new Scene(pane, 300,300));
primaryStage.show();
}
}

Java Painting issues

I need help with a "paint" program. I've got the GUI established, but I'm having issues with the actual drawing portion of the program. Everything I draw disappears immediately after I draw it, and I can't figure out why.
Here is what I have so far:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JPaint extends JFrame implements ActionListener, MouseListener, MouseMotionListener {
int x, y, x2, y2;
private int select = 0;
private Graphics g;
private PaintPanel DrawPanel = new PaintPanel(this);
private JPanel ButtonPanel = new JPanel();
private JTextArea Draw = new JTextArea(20,20);
private JButton jbtRed = new JButton("Red");
private JButton jbtGreen = new JButton("Green");
private JButton jbtBlue = new JButton("Blue");
private JButton jbtErase = new JButton("Eraser");
private JButton jbtClear = new JButton("Clear");
PaintPanel l=new PaintPanel(this);
public JPaint(){
super("Java Paint");
setSize(480,320);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
//build draw panel
DrawPanel.setBackground(Color.WHITE);
add(DrawPanel, BorderLayout.CENTER);
DrawPanel.setVisible(true);
//build button panel
ButtonPanel.add(jbtRed);
ButtonPanel.add(jbtGreen);
ButtonPanel.add(jbtBlue);
ButtonPanel.add(jbtErase);
ButtonPanel.add(jbtClear);
add(ButtonPanel, BorderLayout.SOUTH);
ButtonPanel.setVisible(true);
jbtRed.addActionListener(this);
jbtGreen.addActionListener(this);
jbtBlue.addActionListener(this);
jbtErase.addActionListener(this);
jbtClear.addActionListener(this);
DrawPanel.addMouseMotionListener(this);
DrawPanel.addMouseListener(this);
}
public void actionPerformed(ActionEvent e){
if(e.getSource() == jbtRed){
DrawPanel.setToolTipText("Color set to 'Red'");
select = 1;
}
if(e.getSource() == jbtGreen){
DrawPanel.setToolTipText("Color set to 'Green'");
}
if(e.getSource() == jbtBlue){
DrawPanel.setToolTipText("Color set to 'Blue'");
}
if(e.getSource() == jbtErase){
DrawPanel.setToolTipText("Erase Selected");
}
if(e.getSource() == jbtClear){
DrawPanel.setToolTipText("Drawing cleared");
}
}
#Override
public void mouseDragged(MouseEvent e) {
x = e.getX();
y = e.getY();
DrawPanel.repaint();
}
#Override
public void mouseMoved(MouseEvent e) {
}
#Override
public void mouseClicked(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mousePressed(MouseEvent e) {
x = e.getX();
y = e.getY();
}
#Override
public void mouseReleased(MouseEvent e) {
x2 = e.getX();
y2 = e.getY();
DrawPanel.repaint();
}
}
class PaintPanel extends JPanel
{
JPaint p;
PaintPanel(JPaint in){
p=in;
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
// clear the screen
g.setColor(Color.white);
g.setColor(Color.RED);
g.drawLine(p.x, p.y, p.x2, p.y2);
p.x2 = p.x;
p.y2 = p.y;
}
}
class Run_JPaint {
public static void main(String[] args){
JPaint P = new JPaint();
P.setVisible(true);
}
}
You would probably want to remove the following line of code:
super.paintComponent(g);
from inside your PaintPanel class. Otherwise with each draw command your GUI resets the screen.
Good Luck!

CustomTextbox in Blackberry

Hi friends basically i am a android developer. i am newbie in blackberry development. i need to create the custom text box with image button.
in the right corner of the text box, i want the small image button and it's click listener the text box field should be empty.
i Can create the Custom Text box and also draw bitmap inside the text box. but i can't catch the focus and listener to the image button. please help me
Please give some idea and samples.
I tried this...
MyApp.java Class:
import net.rim.device.api.ui.UiApplication;
public class MyApp extends UiApplication {
public static void main(String[] args) {
MyApp theApp = new MyApp();
theApp.enterEventDispatcher();
}
public MyApp() {
pushScreen(new MyScreen());
}
}
MyScreen.java class:
public final class MyScreen extends MainScreen {
public MyScreen() {
super(Manager.NO_VERTICAL_SCROLL);
setTitle("MyTitle");
VerticalFieldManager vfm = new VerticalFieldManager(
Manager.USE_ALL_HEIGHT | Manager.USE_ALL_HEIGHT);
HorizontalFieldManager hfm = new HorizontalFieldManager(
Manager.USE_ALL_WIDTH);
HorizontalFieldManager hfm1 = new HorizontalFieldManager(
Manager.USE_ALL_WIDTH);
customManager ctm = new customManager(Manager.USE_ALL_WIDTH);
customManager ctm1 = new customManager(Manager.USE_ALL_WIDTH);
hfm.add(ctm);
hfm1.add(ctm1);
vfm.add(hfm);
vfm.add(hfm1);
add(vfm);
}
}
customManager.java Class:
public class customManager extends Manager implements FieldChangeListener {
private Textbox txt;
private Closebtn cls;
Bitmap bitmap;
protected customManager(long style) {
super(style);
// My Coustem TextBOX
txt = new Textbox(300, 100);
// My Coustem Button
cls = new Closebtn();
cls.setChangeListener(this);
add(txt);
add(cls);
}
protected void sublayout(int width, int height) {
setPositionChild(getField(0), 10, 10);
layoutChild(getField(0), getField(0).getPreferredWidth(), getField(0)
.getPreferredHeight());
setPositionChild(getField(1),
getField(0).getWidth() - (getField(1).getWidth()), getField(0)
.getHeight() / 2 - getField(1).getHeight() / 2);
layoutChild(getField(1), getField(1).getWidth(), getField(1)
.getHeight());
setExtent(width, height);
}
public void fieldChanged(Field field, int context) {
txt.setText("");
}
}
Textbox.java Class:
public class Textbox extends Manager {
private int managerWidth;
private int managerHeight;
private int arcWidth;
private VerticalFieldManager vfm = new VerticalFieldManager(
NO_VERTICAL_SCROLL | USE_ALL_WIDTH );
private EditField editField;
private Bitmap bagBitmap;
Textbox(int width, int height, long style) {
super(style | NO_VERTICAL_SCROLL | NO_HORIZONTAL_SCROLL);
managerWidth = width;
managerHeight = height;
long innerStyle = style & (READONLY | FOCUSABLE_MASK); // at least
if (innerStyle == 0) {
innerStyle = FOCUSABLE;
}
editField = new EditField("", "", 10, innerStyle);
arcWidth = editField.getFont().getHeight() & 0xFFFFFFFE; // make it even
EncodedImage en = EncodedImage.getEncodedImageResource("_text.png");
bagBitmap = Util.getScaledBitmapImage(en, width, height);
add(vfm);
vfm.add(editField);
}
public void setFont(Font font) {
super.setFont(font);
editField.setFont(font);
arcWidth = editField.getFont().getHeight() & 0xFFFFFFFE;
updateLayout();
}
Textbox(int width, int height) {
this(width, height, 0L);
}
public String getText() {
return editField.getText();
}
public void setText(String newText) {
editField.setText(newText);
}
public int getPreferredWidth() {
return managerWidth;
}
public int getPreferredHeight() {
return managerHeight;
}
protected void sublayout(int w, int h) {
if (managerWidth == 0) {
managerWidth = w;
}
if (managerHeight == 0) {
managerHeight = h;
}
int actWidth = Math.min(managerWidth, w);
int actHeight = Math.min(managerHeight, h);
layoutChild(vfm, actWidth - arcWidth, actHeight - arcWidth);
setPositionChild(vfm, arcWidth / 2, arcWidth / 2);
setExtent(actWidth, actHeight);
}
protected void paint(Graphics g) {
g.drawBitmap(0, 0, getWidth(), getHeight(), bagBitmap, 0, 0);
super.paint(g);
}
}
Closebtn.java Class:
public class Closebtn extends Field {
private Bitmap bitmap;
public Closebtn() {
super(Manager.FOCUSABLE);
EncodedImage en = EncodedImage.getEncodedImageResource("close.png");
bitmap = Util.getScaledBitmapImage(en, 50, 50);
}
protected void layout(int width, int height) {
setExtent(bitmap.getWidth(), bitmap.getHeight());
}
protected void paint(Graphics graphics) {
graphics.drawBitmap(0, 0, bitmap.getWidth(), bitmap.getHeight(),
bitmap, 0, 0);
}
protected void onFocus(int direction) {
bitmap = bitmap;
}
protected void onUnfocus() {
bitmap = bitmap;
}
protected boolean keyChar(char character, int status, int time) {
if (character == Characters.ENTER) {
clickButton();
return true;
}
return super.keyChar(character, status, time);
}
protected boolean navigationClick(int status, int time) {
clickButton();
return true;
}
protected boolean trackwheelClick(int status, int time) {
clickButton();
return true;
}
protected boolean invokeAction(int action) {
switch (action) {
case ACTION_INVOKE: {
clickButton();
return true;
}
}
return super.invokeAction(action);
}
public void setDirty(boolean dirty) {
}
public void setMuddy(boolean muddy) {
}
public void clickButton() {
fieldChangeNotify(0);
}
}
Util.java Class:
public class Util {
public static Bitmap getScaledBitmapImage(EncodedImage image, int width,
int height) {
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();
}
}
My problem is i can't add more then one fields here Pls help me..
Try this custom class:
public class TextFieldWithClear extends HorizontalFieldManager {
protected HorizontalFieldManager hfmEditTextPanel;
protected LabelField lblEditText;
protected EditField textField;
protected MyImageButton bitmapFieldClear;
int mHeight;
int mWidth;
String mLabel;
public TextFieldWithClear(String label, int width, int height) {
super(FOCUSABLE);
Border border = BorderFactory
.createSimpleBorder(new XYEdges(2, 2, 2, 2));
this.setBorder(border);
Background bg = BackgroundFactory.createSolidBackground(Color.WHITE);
this.setBackground(bg);
mWidth = width;
mHeight = height;
mLabel = label;
lblEditText = new LabelField(mLabel) {
protected void paint(Graphics graphics) {
graphics.setColor(0x4B4B4B);
super.paint(graphics);
}
};
add(lblEditText);
hfmEditTextPanel = new HorizontalFieldManager(FOCUSABLE
| VERTICAL_SCROLL | VERTICAL_SCROLLBAR) {
protected void sublayout(int maxWidth, int maxHeight) {
maxWidth = mWidth - 30;
maxHeight = mHeight;
super.sublayout(maxWidth, maxHeight);
setExtent(maxWidth, maxHeight);
}
};
textField = new EditField() {
// protected void layout(int width, int height)
// {
// width = mWidth - 50;
// height=35;
// super.layout(width, height);
// //setExtent(width, height);
// }
};
hfmEditTextPanel.add(textField);
add(hfmEditTextPanel);
bitmapFieldClear = new MyImageButton(
Bitmap.getBitmapResource("btn_delete_normal.png"),
Bitmap.getBitmapResource("btn_delete_focused.png"));
bitmapFieldClear.setChangeListener(buttonListener);
add(bitmapFieldClear);
}
public String getText() {
String value = "";
if (textField.getText().length() > 0)
value = textField.getText();
return value;
}
public void setString(String value) {
if (value != null) {
textField.setText(value);
}
}
FieldChangeListener buttonListener = new FieldChangeListener() {
public void fieldChanged(Field field, int context) {
textField.clear(0);
textField.setFocus();
}
};
public void onUndisplay()
{
textField.setEditable(false);
}
public void onDisplay()
{
textField.setEditable(true);
}
}
This is not easy to do just overriding EditField, so this is what I'd try:
Use an horizontal manager (for instance, HorizontalFieldManager or other custom manager, perhaps with fixed column widths. This manager would have two fields inside: at left an EditField, at right a custom buttonfield.
Set a Background to the manager. The bg would draw the green background as well as the blue border. You can use an scaled bitmap (have a look at BackgroundFactory.createBitmapBackground).
Create a new EditField subclass, and override its paintBackground method so that it does nothing. If it does not work, try overriding paint so that it does only draw the text. This is the trickiest part.
Create a custom Buttonfield subclass with the cross over gray circle image. You can read a good tutorial on how to do that here. You also have available an already made BitmapButtonField in the Advanced Ui Library. When the button is clicked, it would invoke EditField.setText("") on the EditField.

Resources