我正在研究自定义键盘应用程序
这是softkeyboard中input.xml的背景颜色代码: –
@Override public View onCreateInputView() { Log.e("onStartInputView ","On StartInput View Called--"); SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); String Backgroundcolour = preferences.getString("BackgroundColour",""); Log.e("Brithnesss- -","----"+Backgroundcolour); if(Backgroundcolour.equalsIgnoreCase("black")) { this.mInputView = (KeyboardView) getLayoutInflater().inflate( R.layout.input,null); }else { this.mInputView = (KeyboardView) getLayoutInflater().inflate( R.layout.input1,null); //this.mInputView.setB } this.mInputView.setOnKeyboardActionListener(this); this.mInputView.setKeyboard(this.mQwertyKeyboard); return this.mInputView; } @Override public void onStartInputView(EditorInfo attribute,boolean restarting) { super.onStartInputView(attribute,restarting); // Apply the selected keyboard to the input view. setInputView(onCreateInputView()); }
我没有得到如何设置特定键的背景图像.
解决方法
例如,有一个
small downloadable project可以创建自定义数字键盘.对于CustomKeyboardView类或您自己的自定义键盘类,添加如下方法.它会覆盖onDraw()方法并绘制使用代码7(在本例中为“0”)红色定义的键的背景,并将所有其他键绘制为蓝色.
@Override public void onDraw(Canvas canvas) { super.onDraw(canvas); List<Key> keys = getKeyboard().getKeys(); for (Key key : keys) { if (key.codes[0] == 7) { Log.e("KEY","Drawing key with code " + key.codes[0]); Drawable dr = (Drawable) context.getResources().getDrawable(R.drawable.red_tint); dr.setBounds(key.x,key.y,key.x + key.width,key.y + key.height); dr.draw(canvas); } else { Drawable dr = (Drawable) context.getResources().getDrawable(R.drawable.blue_tint); dr.setBounds(key.x,key.y + key.height); dr.draw(canvas); } } }
在这种情况下,我没有使用9-patch图像,只是一些简单的50%透明方形图像,并且实现了现有按钮仅仅用我想要的颜色着色的效果.为了获得更自定义的结果,我可以制作我的背景可绘制9补丁图像并执行以下操作.请注意,带有图标的两个键无法正确呈现,因为图标未定义为9-patch图像,并且我没有做出任何特别的努力来允许它们在此示例中很好地扩展.我也没有解决对各种状态的键使用不同的图像/效果;其他人已经证明了如何做到这一点.
@Override public void onDraw(Canvas canvas) { // super.onDraw(canvas); List<Key> keys = getKeyboard().getKeys(); for (Key key : keys) { if (key.codes[0] == 7) { NinePatchDrawable npd = (NinePatchDrawable) context.getResources().getDrawable(R.drawable.red_key); npd.setBounds(key.x,key.y + key.height); npd.draw(canvas); } else { NinePatchDrawable npd = (NinePatchDrawable) context.getResources().getDrawable(R.drawable.blue_key); npd.setBounds(key.x,key.y + key.height); npd.draw(canvas); } Paint paint = new Paint(); paint.setTextAlign(Paint.Align.CENTER); paint.setTextSize(48); paint.setColor(Color.GRAY); if (key.label != null) { canvas.drawText(key.label.toString(),key.x + (key.width / 2),key.y + (key.height / 2),paint); } else { key.icon.setBounds(key.x,key.y + key.height); key.icon.draw(canvas); } } }