基本上我想在Android中做这样的事情:
我尝试在自定义 EditText 中绘制水平线,然后在这些线上键入。
我使用文字大小作为两条水平线之间的距离。但是,光标的大小和文本的大小不一样。因此,我无法维持在这些行上“放置”文本。
文本库与这些水平线的对齐方式并不合适。
以下是用于绘制线条的代码: -
float textSize = getTextSize());
Paint paint = new Paint();
for (int i = 0; i < 50; i++) {
canvas.drawLine(0, textSize * i, getWidth(), textSize * i, paint);
}
EditText没有提供任何获取游标大小的方法。
请建议是否有任何解决方法,或任何其他更好的方法。
答案 0 :(得分:4)
public class LinedEditText extends EditText {
private Rect mRect;
private Paint mPaint;
// we need this constructor for LayoutInflater
public LinedEditText(Context context, AttributeSet attrs) {
super(context, attrs);
mRect = new Rect();
mPaint = new Paint();
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setColor(0x800000FF);
}
@Override
protected void onDraw(Canvas canvas) {
int count = getLineCount();
Rect r = mRect;
Paint paint = mPaint;
for (int i = 0; i < count; i++) {
int baseline = getLineBounds(i, r);
canvas.drawLine(r.left, baseline + 1, r.right, baseline + 1, paint);
}
super.onDraw(canvas);
}
}
现在使用 LinedEditText 类的对象。
public class HorizontalLine extends Activity{
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle("Android: Ruled/horizonal lines in Textview");
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
LayoutParams textViewLayoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
LinedEditText et = new LinedEditText(this, null);
et.setText("The name of our country is Bangladesh. I am proud of my country :)");
et.setLayoutParams(textViewLayoutParams);
ll.addView(et);
this.setContentView(ll);
}
}