问题
Suppose I had a custombuttonField which contains 2 bitmap pictures, say 2 arrows(one in left and the other in right) and when the user clicks on this button the color of the arrow should become red in my application. I m doing this by pushing the same screen on click evevt. I m using a int variable pic_status which determines which picture should be loaded on the custombutonfield on calling the pushScreen(). Is there any way to update the customButtonField (update the bitmap) from the same screen without calling pushScreen().
public void fieldChanged(Field field, int context)
{
if(field == bf1)
{
if(pic_status == 0)
{
b =1;
}
UiApplication.getUiApplication().pushScreen(new Screen2(b));
}
In my above code u have seen that i m pushing the same screen if the user clicks the button. Plz give the code to update it without calling pushScreen().
回答1:
Below code for the customButtonField which have a two image. One for the focus image and other for the normal image.
to update the button image, you just need to call setBitmap method for normal image. You can modify below code according to you. You need to call invalidate() method after calling the setBitmap method.
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.component.BitmapField;
import net.rim.device.api.ui.component.LabelField;
class BitmapButtonField extends BitmapField
{
Bitmap mNormal;
Bitmap mFocused;
String text;
int mWidth;
int mHeight;
public Bitmap bitmap = null;
public BitmapButtonField(String text,Bitmap normal, Bitmap focused)
{
super(normal,FOCUSABLE);
mNormal = normal;
mFocused = focused;
mWidth = mNormal.getWidth();
mHeight = mNormal.getHeight();
this.text=text;
setMargin(0, 0, 0, 0);
setPadding(0, 0, 0, 0);
}
public void setBitmap(Bitmap bitmap)
{
mNormal=bitmap;
this.bitmap=bitmap;
}
public void setfocusBitmap(Bitmap bitmap)
{
mFocused=bitmap;
}
public String getText()
{
return text;
}
public void setText(String text)
{
this.text=text;
}
protected void paint(Graphics graphics) {
Bitmap bitmap = mNormal;
if(isFocus())
{
bitmap = mFocused;
}
else
{
bitmap = mNormal;
}
graphics.drawBitmap(0, 0, bitmap.getWidth(), bitmap.getHeight(),
bitmap, 0, 0);
LabelField l=new LabelField(text);
graphics.drawText(text, bitmap.getWidth()/2-l.getPreferredWidth()/2+3, bitmap.getHeight()/2-l.getPreferredHeight()/2);
}
protected void drawFocus(Graphics graphics, boolean on) {
}
protected void onFocus(int direction) {
invalidate();
super.onFocus(direction);
}
protected void onUnfocus() {
invalidate();
super.onUnfocus();
}
public int getPreferredWidth() {
return mWidth;
}
public int getPreferredHeight() {
return mHeight;
}
protected void layout(int width, int height) {
setExtent(mWidth, mHeight);
}
}
来源:https://stackoverflow.com/questions/6517411/about-custombuttonfield-in-blackberry