我之前曾提出一个问题,标题为“Android: Ruled/horizonal lines in TextView”,链接在这里。但是我没有得到所需的答案。所以我计划通过Java在TextView上画线来实现。有没有办法在TextView内部画线?或者如果我从Java代码中获取行末,那么我就可以为每一行添加一个TextView。非常感谢您的帮助。
我正在使用在EditText
的每一行之间绘制线条的技术,然后通过将setKeyListener(null)
设置为自定义EditText对象来使其不可编辑,这样,EditText就像一个TextView
:)
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);
我不知道为什么你想在TextView中添加一条线。如果你想要绘制一条水平的单线,只需将此代码放置在你从数据库中读取的TextView之间,显然是在你的布局XML文件中:
<View android:background="#colorYouWant" android:layout_width = "fill_parent" android:layout_height="1dip" android:id="+@id/horizontalLine"/>
通过相关的Java代码调整分隔符:
View horizontalLine = (View)findViewById(R.id.horizontalLine);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
lp.setMargins(left, top, right, bottom);
horizontalLine.setLayoutParams(lp);
你需要更改的参数是左、上、右、下。