在画布上使用EditText [英] Use EditText on Canvas
问题描述
我正在开发一个应用程序,需要在画布上绘制一个EditText。我能够做到这一点,但是
我只能看到它,而不使用它。这是我初始化EditText的方式
I'm developing an app where I need to draw a EditText on my canvas. I was able to do this, but
I can just see it, not use it. Here is how I've initialized the EditText
et = new EditText(MyActivity.this);
et.setText("edittext");
et.setBackgroundColor(Color.GRAY);
et.requestFocus();
//add it to a LinearLayout
layout.addview(et);
要使EditText实际可用,我缺少什么?
what am I missing to make the EditText actually usable?
推荐答案
您可以使用此代码,在 main
中将此方法添加到获取输入键:
You might use this code, in main
add this method to get input keys:
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
cv = (CustomView) findViewById(R.id.custom_view);
cv.dispatchKeyEvent(event);
return super.dispatchKeyEvent(event);
}
在类中扩展了视图类:
@Override
protected void onDraw(Canvas canvas){
super.onDraw(canvas);
Paint p = new Paint();
p.setTextSize(36);
LinearLayout layout = new LinearLayout(this.getContext());
EditText textView = new EditText(this.getContext());
textView.setVisibility(View.VISIBLE);
textView.setText(key);
textView.setX(x);//get x from onTouch method
textView.setY(y); // get y from onTouch method
layout.addView(textView);
layout.measure(canvas.getWidth(), canvas.getHeight());
layout.layout(50,50, canvas.getWidth(), canvas.getHeight());
layout.draw(canvas);
}
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
int keyaction = event.getAction();
if(keyaction == event.ACTION_DOWN)
{
int keyunicode = event.getUnicodeChar(event.getMetaState() );
char character = (char) keyunicode;
key += character;
System.out.println("DEBUG MESSAGE KEY=" + character);
}
// you might add if (delete)
// https://stackoverflow.com/questions/7438612/how-to-remove-the-last-character-from-a-string
// method to delete last character
invalidate();
return super.dispatchKeyEvent(event);
}
您需要将文本存储在一个对象中,该对象包含 x,y,宽度,高度,字符串
You will need to store the text in an object, this object contains x, y, width, height, string
在 onTouch
方法,检查单击是否在同一文本中,然后使 new EditText>> false
并修改旧密钥。
in the onTouch
method, check if the click is in the same text, then make new EditText >> false
and make the old key to be modified.
这篇关于在画布上使用EditText的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!