2

在我的 android-app 中,我试图创建一个带有两行文本的按钮。一个将显示(短)单击时按钮正在做什么,另一个应显示长按时的效果,并且该按钮可以长按。就像在安卓系统的标准键盘上一样(见图

我试过的:

Bitmap canvasBitmap = Bitmap.createBitmap(64, 24, Bitmap.Config.ARGB_8888);
Canvas imageCanvas = new Canvas(canvasBitmap);
Paint imagePaint = new Paint();
imagePaint.setTextAlign(Align.CENTER);
imagePaint.setTextSize(14f);
imageCanvas.drawText(String, pxwidth/2, pxheight, imagePaint);
image = new BitmapDrawable(canvasBitmap);
((TextView) findViewById(R.id.button)).setCompoundDrawables(null,image,null,null);

但我当前的 API 版本(API 9 / GINGERBREAD / Android 2.3)不支持它
你能帮帮我吗?

4

2 回答 2

1

如果您需要以 9 为目标,则不能使用该功能,您需要使用另一种技术。我能想到的一种方法是使用 ImageButton 而不是按钮,预渲染整个按钮的图像,并将其应用于 xml 中的新 ImageButton。

于 2013-03-13T21:05:20.627 回答
0

我用这个Custom View作为解决方案(感谢 Gabe Sechan 的想法):

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.util.AttributeSet;
import android.widget.Button;

class LongClickButton extends Button {
    private String mLongClickString;
    private String mOnLongClick;
    private Paint mTextPaint;
    public LongClickButton(Context context, AttributeSet attrs){
        super(context, attrs);

        mTextPaint = new Paint();
        mTextPaint.setTextSize(this.getTextSize()/2);
        mTextPaint.setColor(Color.DKGRAY);
        mTextPaint.setShadowLayer(0, 1, 1, Color.GRAY);
        mTextPaint.setTextAlign(Align.RIGHT);

        TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.LongClickButton, 0, 0);
        try{
            mLongClickString = a.getString(R.styleable.LongClickButton_longClickText);
            mOnLongClick = a.getString(R.styleable.LongClickButton_onLongClick);
        } finally {
            a.recycle();
        }
    }
    public String getLongClickString(){
        return mLongClickString;
    }
    public String getOnLongClick(){
        return mOnLongClick;
    }
    public void setLongClickString(String LongClickString){
        mLongClickString = LongClickString;
        invalidate();
        requestLayout();
    }
    public void setOnLongClick(String OnLongClick){
        mOnLongClick = OnLongClick;
        invalidate();
        requestLayout();
    }
    @Override
    public void onDraw(Canvas canvas){
        super.onDraw(canvas);
        canvas.drawText(mLongClickString, this.getWidth()-(this.getPaddingRight()/4*3), (this.getPaddingTop()/2)+mTextPaint.getTextSize(), mTextPaint);
    }
}
于 2013-03-14T12:44:39.110 回答