我正在使用在 EditText 中的每一行文本之间画线的技术,然后我将通过设置 setKeyListener( null) 到自定义的 EditText 对象,这样 EditText 就像一个 TextView :)
一个自定义的EditText,在显示的每行文本之间画线:
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);
}
}
现在在您需要 TextView 的地方使用 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);
et.setKeyListener(null);
ll.addView(et);
this.setContentView(ll);
}
}
et.setKeyListener(null) 使 EditText 不可编辑,因此它的作用类似于 TextView。
输出:
光标问题:
如果您只使用 et.setKeyListener(null) 那么它只是不听键,而是
用户可以在 EditText 上看到一个光标。如果您不想要此光标,只需添加以下行即可禁用 EditText:
et.setEnabled(false);