如何在android的键盘中实现键盘视图中的OnBufferDraw()

时间:2015-05-20 05:51:12

标签: java android keyboard android-softkeyboard

我正在尝试自定义我的字体,到目前为止已找到使用onBufferDraw()方法的解决方案。我从这个链接检索方法: https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/inputmethodservice/KeyboardView.java

尝试使用我自己的自定义字体的函数,并在我的xml中添加了类作为键盘视图。

public class MyKeyboardView extends KeyboardView {

private boolean caps = false;
private Keyboard keyboard;


 private static final boolean DEBUG = false;
    private static final int NOT_A_KEY = -1;
    private static final int[] KEY_DELETE = { Keyboard.KEYCODE_DELETE };
    private static final int[] LONG_PRESSABLE_STATE_SET = { R.attr.state_long_pressable };   

    private Keyboard mKeyboard;
    private int mCurrentKeyIndex = NOT_A_KEY;
    private int mLabelTextSize;
    private int mKeyTextSize;
    private int mKeyTextColor;
    private float mShadowRadius;
    private int mShadowColor;
    private float mBackgroundDimAmount;

    private TextView mPreviewText;
    private PopupWindow mPreviewPopup;
    private int mPreviewTextSizeLarge;
    private int mPreviewOffset;
    private int mPreviewHeight;
    // Working variable
    private final int[] mCoordinates = new int[2];
    private PopupWindow mPopupKeyboard;
    private View mMiniKeyboardContainer;
    private KeyboardView mMiniKeyboard;
    private boolean mMiniKeyboardOnScreen;
    private View mPopupParent;
    private int mMiniKeyboardOffsetX;
    private int mMiniKeyboardOffsetY;
    private Map<Key,View> mMiniKeyboardCache;
    private Key[] mKeys;
    /** Listener for {@link OnKeyboardActionListener}. */
    private OnKeyboardActionListener mKeyboardActionListener;

    private static final int MSG_SHOW_PREVIEW = 1;
    private static final int MSG_REMOVE_PREVIEW = 2;
    private static final int MSG_REPEAT = 3;
    private static final int MSG_LONGPRESS = 4;
    private static final int DELAY_BEFORE_PREVIEW = 0;
    private static final int DELAY_AFTER_PREVIEW = 70;
    private static final int DEBOUNCE_TIME = 70;

    private int mVerticalCorrection;
    private int mProximityThreshold;
    private boolean mPreviewCentered = false;
    private boolean mShowPreview = true;
    private boolean mShowTouchPoints = true;
    private int mPopupPreviewX;
    private int mPopupPreviewY;
    private int mLastX;
    private int mLastY;
    private int mStartX;
    private int mStartY;
    private boolean mProximityCorrectOn;

    private Paint mPaint;
    private Rect mPadding;

    private long mDownTime;
    private long mLastMoveTime;
    private int mLastKey;
    private int mLastCodeX;
    private int mLastCodeY;
    private int mCurrentKey = NOT_A_KEY;
    private int mDownKey = NOT_A_KEY;
    private long mLastKeyTime;
    private long mCurrentKeyTime;
    private int[] mKeyIndices = new int[12];
    private GestureDetector mGestureDetector;
    private int mPopupX;
    private int mPopupY;
    private int mRepeatKeyIndex = NOT_A_KEY;
    private int mPopupLayout;
    private boolean mAbortKey;
    private Key mInvalidatedKey;
    private Rect mClipRegion = new Rect(0, 0, 0, 0);
    private boolean mPossiblePoly;

    private int mSwipeThreshold;
    private boolean mDisambiguateSwipe;
    // Variables for dealing with multiple pointers
    private int mOldPointerCount = 1;
    private float mOldPointerX;
    private float mOldPointerY;
    private Drawable mKeyBackground;
    private static final int REPEAT_INTERVAL = 50; // ~20 keys per second
    private static final int REPEAT_START_DELAY = 400;

    private static int MAX_NEARBY_KEYS = 12;
    private int[] mDistances = new int[MAX_NEARBY_KEYS];
    // For multi-tap
    private int mLastSentIndex;
    private int mTapCount;
    private long mLastTapTime;
    private boolean mInMultiTap;
    private static final int MULTITAP_INTERVAL = 800; // milliseconds
    private StringBuilder mPreviewLabel = new StringBuilder(1);
    /** Whether the keyboard bitmap needs to be redrawn before it's blitted. **/
    private boolean mDrawPending;
    /** The dirty region in the keyboard bitmap */
    private Rect mDirtyRect = new Rect();
    /** The keyboard bitmap for faster updates */
    private Bitmap mBuffer;
    /** Notes if the keyboard just changed, so that we could possibly reallocate the mBuffer. */
    private boolean mKeyboardChanged;
    /** The canvas for the above mutable keyboard bitmap */
    private Canvas mCanvas;




public MyKeyboardView(Context context, AttributeSet attrs) {
    super(context, attrs);
    // TODO Auto-generated constructor stub

}




public void _setKeyboard(Keyboard kv)
{
    this.keyboard=kv;



}


 public MyKeyboardView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        TypedArray a =
            context.obtainStyledAttributes(
                attrs, R.styleable.KeyboardView, defStyle, 0);
        LayoutInflater inflate =
                (LayoutInflater) context
                        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        int previewLayout = 0;
        int keyTextSize = 0;
        int n = a.getIndexCount();

        for (int i = 0; i < n; i++) {
            int attr = a.getIndex(i);
            switch (attr) {
            case R.styleable.KeyboardView_keyBackground:
                mKeyBackground = a.getDrawable(attr);
                break;
            case R.styleable.KeyboardView_verticalCorrection:
                mVerticalCorrection = a.getDimensionPixelOffset(attr, 0);
                break;
            case R.styleable.KeyboardView_keyPreviewLayout:
                previewLayout = a.getResourceId(attr, 0);
                break;
            case R.styleable.KeyboardView_keyPreviewOffset:
                mPreviewOffset = a.getDimensionPixelOffset(attr, 0);
                break;
            case R.styleable.KeyboardView_keyPreviewHeight:
                mPreviewHeight = a.getDimensionPixelSize(attr, 80);
                break;
            case R.styleable.KeyboardView_keyTextSize:
                mKeyTextSize = a.getDimensionPixelSize(attr, 18);
                break;
            case R.styleable.KeyboardView_keyTextColor:
                mKeyTextColor = a.getColor(attr, 0xFF000000);
                break;
            case R.styleable.KeyboardView_labelTextSize:
                mLabelTextSize = a.getDimensionPixelSize(attr, 14);
                break;
            case R.styleable.KeyboardView_popupLayout:
                mPopupLayout = a.getResourceId(attr, 0);
                break;
            case R.styleable.KeyboardView_shadowColor:
                mShadowColor = a.getColor(attr, 0);
                break;
            case R.styleable.KeyboardView_shadowRadius:
                mShadowRadius = a.getFloat(attr, 0f);
                break;
            }
        }

       // a = mContext.obtainStyledAttributes(R.styleable.Theme);
        mBackgroundDimAmount = a.getFloat(R.styleable.Theme_backgroundDimAmount, 0.5f);
        mPreviewPopup = new PopupWindow(context);
        if (previewLayout != 0) {
            mPreviewText = (TextView) inflate.inflate(previewLayout, null);
            mPreviewTextSizeLarge = (int) mPreviewText.getTextSize();
            mPreviewPopup.setContentView(mPreviewText);
            mPreviewPopup.setBackgroundDrawable(null);
        } else {
            mShowPreview = false;
        }

        mPreviewPopup.setTouchable(false);

        mPopupKeyboard = new PopupWindow(context);
        mPopupKeyboard.setBackgroundDrawable(null);
        //mPopupKeyboard.setClippingEnabled(false);

        mPopupParent = this;
        //mPredicting = true;

        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mPaint.setTextSize(keyTextSize);
        mPaint.setTextAlign(Align.CENTER);
        mPaint.setAlpha(255);
        mPadding = new Rect(0, 0, 0, 0);
        mMiniKeyboardCache = new HashMap<Key,View>();
        mKeyBackground.getPadding(mPadding);
        mSwipeThreshold = (int) (500 * getResources().getDisplayMetrics().density);

    }



@Override
public void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    if (mDrawPending || mBuffer == null || mKeyboardChanged) {
        onBufferDraw();
    }
    canvas.drawBitmap(mBuffer, 0, 0, null);


    Paint paint = new Paint();
    paint.setTextAlign(Paint.Align.CENTER);
    paint.setTextSize(25);
    paint.setColor(Color.BLACK);

    Typeface custom_font = Typeface.createFromAsset(getContext().getAssets(), "fonts/Roboto-Bold.ttf");

    paint.setTypeface(custom_font);




    List<Key> keys = getKeyboard().getKeys();


    for(Key key: keys) {




        if(key.label != null)
        {

        if(key.label.toString().equals("q") || key.label.toString().equals("Q") )   
            canvas.drawText(String.valueOf(1), key.x + (key.width/2)+10, key.y + 25, paint);

        else if(key.label.toString().equals("w") || key.label.toString().equals("W") )  
            canvas.drawText(String.valueOf(2), key.x + (key.width/2)+10, key.y + 25, paint);

        else if(key.label.toString().equals("e") || key.label.toString().equals("E") )  
            canvas.drawText(String.valueOf(3), key.x + (key.width/2)+10, key.y + 25, paint);

        else if(key.label.toString().equals("r") || key.label.toString().equals("R") )  
            canvas.drawText(String.valueOf(4), key.x + (key.width/2)+10, key.y + 25, paint);

        else if(key.label.toString().equals("t") || key.label.toString().equals("T") )  
            canvas.drawText(String.valueOf(5), key.x + (key.width/2)+10, key.y + 25, paint);

        else if(key.label.toString().equals("y") || key.label.toString().equals("Y") )  
            canvas.drawText(String.valueOf(6), key.x + (key.width/2)+10, key.y + 25, paint);

        else if(key.label.toString().equals("u") || key.label.toString().equals("U") )  
            canvas.drawText(String.valueOf(7), key.x + (key.width/2)+10, key.y + 25, paint);

        else if(key.label.toString().equals("i") || key.label.toString().equals("I") )  
            canvas.drawText(String.valueOf(8), key.x + (key.width/2)+10, key.y + 25, paint);

        else if(key.label.toString().equals("o") || key.label.toString().equals("o") )  
            canvas.drawText(String.valueOf(9), key.x + (key.width/2)+10, key.y + 25, paint);

        else if(key.label.toString().equals("p") || key.label.toString().equals("P") )  
            canvas.drawText(String.valueOf(0), key.x + (key.width/2)+10, key.y + 25, paint);
        else
        {




        }





        }




   }
}



private void onBufferDraw() {
    if (mBuffer == null || mKeyboardChanged) {
        if (mBuffer == null || mKeyboardChanged &&
                (mBuffer.getWidth() != getWidth() || mBuffer.getHeight() != getHeight())) {
            // Make sure our bitmap is at least 1x1
            final int width = Math.max(1, getWidth());
            final int height = Math.max(1, getHeight());
            mBuffer = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
            mCanvas = new Canvas(mBuffer);
        }
        invalidateAllKeys();
        mKeyboardChanged = false;
    }
    final Canvas canvas = mCanvas;
    canvas.clipRect(mDirtyRect, Op.REPLACE);

    if (mKeyboard == null) return;

    final Paint paint = mPaint;
    final Drawable keyBackground = mKeyBackground;
    final Rect clipRegion = mClipRegion;
    final Rect padding = mPadding;

    final Key[] keys = mKeys;
    final Key invalidKey = mInvalidatedKey;
    paint.setColor(mKeyTextColor);
    boolean drawSingleKey = false;


    final int keyCount = keys.length;
    for (int i = 0; i < keyCount; i++) {
        final Key key = keys[i];
        if (drawSingleKey && invalidKey != key) {
            continue;
        }
        int[] drawableState = key.getCurrentDrawableState();
        keyBackground.setState(drawableState);
        // Switch the character to uppercase if shift is pressed
        String label = key.label == null? null : adjustCase(key.label).toString();

        final Rect bounds = keyBackground.getBounds();
        if (key.width != bounds.right || 
                key.height != bounds.bottom) {
            keyBackground.setBounds(0, 0, key.width, key.height);
        }

        keyBackground.draw(canvas);
        Typeface custom_font = Typeface.createFromAsset(getContext().getAssets(), "fonts/Roboto-Bold.ttf");
        if (label != null) {
            // For characters, use large font. For labels like "Done", use small font.
            if (label.length() > 1 && key.codes.length < 2) {
                paint.setTextSize(mLabelTextSize);
                paint.setTypeface(custom_font);
            } else {
                paint.setTextSize(mKeyTextSize);
                paint.setTypeface(custom_font);
            }
            // Draw a drop shadow for the text
            paint.setShadowLayer(mShadowRadius, 0, 0, mShadowColor);
            // Draw the text
            canvas.drawText(label,
                (key.width - padding.left - padding.right) / 2
                        + padding.left,
                (key.height - padding.top - padding.bottom) / 2
                        + (paint.getTextSize() - paint.descent()) / 2 + padding.top,
                paint);
            // Turn off drop shadow
            paint.setShadowLayer(0, 0, 0, 0);
        } else if (key.icon != null) {
            final int drawableX = (key.width - padding.left - padding.right 
                            - key.icon.getIntrinsicWidth()) / 2 + padding.left;
            final int drawableY = (key.height - padding.top - padding.bottom 
                    - key.icon.getIntrinsicHeight()) / 2 + padding.top;
            canvas.translate(drawableX, drawableY);
            key.icon.setBounds(0, 0, 
                    key.icon.getIntrinsicWidth(), key.icon.getIntrinsicHeight());
            key.icon.draw(canvas);
            canvas.translate(-drawableX, -drawableY);
        }
              }
    mInvalidatedKey = null;
    // Overlay a dark rectangle to dim the keyboard
    if (mMiniKeyboardOnScreen) {
        paint.setColor((int) (mBackgroundDimAmount * 0xFF) << 24);
        canvas.drawRect(0, 0, getWidth(), getHeight(), paint);
    }
    if (DEBUG && mShowTouchPoints) {
        paint.setAlpha(128);
        paint.setColor(0xFFFF0000);
        canvas.drawCircle(mStartX, mStartY, 3, paint);
        canvas.drawLine(mStartX, mStartY, mLastX, mLastY, paint);
        paint.setColor(0xFF0000FF);
        canvas.drawCircle(mLastX, mLastY, 3, paint);
        paint.setColor(0xFF00FF00);
        canvas.drawCircle((mStartX + mLastX) / 2, (mStartY + mLastY) / 2, 2, paint);
    }

    mDrawPending = false;
    mDirtyRect.setEmpty();
}


private CharSequence adjustCase(CharSequence label) {
    if (mKeyboard.isShifted() && label != null && label.length() < 3
            && Character.isLowerCase(label.charAt(0))) {
        label = label.toString().toUpperCase();
    }
    return label;
}

XML

<com.main.MyKeyboardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/keyboard1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/buttons"
    android:keyBackground="@color/background_color"
    android:keyTextColor="#000000"
    android:keyTextSize="26sp"
    android:keyPreviewLayout ="@layout/preview"
    android:background="#FFFFFF"
/>  

但什么都没发生!我不知道为什么以及我缺少什么来改变字体。

0 个答案:

没有答案